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 static char time_now_string
[64] = {0}; // Current time as a string.
106 static int time_changed
= 0; // time_now changed
107 char main_quit
= 0; // True if we're in the process of exiting.
108 static char main_reload
= 0; // Re-load pending
109 linked_list
*loaded_plugins
;
110 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
112 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
113 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
115 config_descriptt config_values
[] = {
116 CONFIG("debug", debug
, INT
),
117 CONFIG("log_file", log_filename
, STRING
),
118 CONFIG("pid_file", pid_file
, STRING
),
119 CONFIG("random_device", random_device
, STRING
),
120 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
121 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
122 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
123 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
124 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
125 CONFIG("primary_dns", default_dns1
, IPv4
),
126 CONFIG("secondary_dns", default_dns2
, IPv4
),
127 CONFIG("primary_radius", radiusserver
[0], IPv4
),
128 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
129 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
130 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
131 CONFIG("radius_accounting", radius_accounting
, BOOL
),
132 CONFIG("radius_interim", radius_interim
, INT
),
133 CONFIG("radius_secret", radiussecret
, STRING
),
134 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
135 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
136 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
137 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
138 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
139 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
140 CONFIG("guest_account", guest_user
, STRING
),
141 CONFIG("bind_address", bind_address
, IPv4
),
142 CONFIG("peer_address", peer_address
, IPv4
),
143 CONFIG("send_garp", send_garp
, BOOL
),
144 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
145 CONFIG("throttle_buckets", num_tbfs
, INT
),
146 CONFIG("accounting_dir", accounting_dir
, STRING
),
147 CONFIG("dump_speed", dump_speed
, BOOL
),
148 CONFIG("multi_read_count", multi_read_count
, INT
),
149 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
150 CONFIG("lock_pages", lock_pages
, BOOL
),
151 CONFIG("icmp_rate", icmp_rate
, INT
),
152 CONFIG("packet_limit", max_packets
, INT
),
153 CONFIG("cluster_address", cluster_address
, IPv4
),
154 CONFIG("cluster_interface", cluster_interface
, STRING
),
155 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
156 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
157 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
158 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
159 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
160 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
161 CONFIG("hostname", hostname
, STRING
),
162 CONFIG("nexthop_address", nexthop_address
, IPv4
),
163 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
167 static char *plugin_functions
[] = {
172 "plugin_new_session",
173 "plugin_kill_session",
175 "plugin_radius_response",
176 "plugin_radius_reset",
177 "plugin_radius_account",
178 "plugin_become_master",
179 "plugin_new_session_master",
182 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
184 // Counters for shutdown sessions
185 static sessiont shut_acct
[8192];
186 static sessionidt shut_acct_n
= 0;
188 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
189 bundlet
*bundle
= NULL
; // Array of bundle structures.
190 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
191 sessiont
*session
= NULL
; // Array of session structures.
192 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
193 radiust
*radius
= NULL
; // Array of radius structures.
194 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
195 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
196 static controlt
*controlfree
= 0;
197 struct Tstats
*_statistics
= NULL
;
199 struct Tringbuffer
*ringbuffer
= NULL
;
202 static ssize_t
netlink_send(struct nlmsghdr
*nh
);
203 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
);
204 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
205 static void uncache_ipmap(in_addr_t ip
);
206 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
207 static void free_ip_address(sessionidt s
);
208 static void dump_acct_info(int all
);
209 static void sighup_handler(int sig
);
210 static void shutdown_handler(int sig
);
211 static void sigchild_handler(int sig
);
212 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
213 static void update_config(void);
214 static void read_config_file(void);
215 static void initplugins(void);
216 static int add_plugin(char *plugin_name
);
217 static int remove_plugin(char *plugin_name
);
218 static void plugins_done(void);
219 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
220 static tunnelidt
new_tunnel(void);
221 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
222 static void bundleclear(bundleidt b
);
224 // on slaves, alow BGP to withdraw cleanly before exiting
227 // quit actions (master)
228 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
229 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
231 // return internal time (10ths since process startup), set f if given
232 // as a side-effect sets time_now, and time_changed
233 static clockt
now(double *f
)
237 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
238 if (t
.tv_sec
!= time_now
)
243 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
246 // work out a retry time based on try number
247 // This is a straight bounded exponential backoff.
248 // Maximum re-try time is 32 seconds. (2^5).
249 clockt
backoff(uint8_t try)
251 if (try > 5) try = 5; // max backoff
252 return now(NULL
) + 10 * (1 << try);
257 // Log a debug message. Typically called via the LOG macro
259 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
261 static char message
[65536] = {0};
267 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
268 ringbuffer
->tail
= 0;
269 if (ringbuffer
->tail
== ringbuffer
->head
)
270 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
271 ringbuffer
->head
= 0;
273 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
274 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
275 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
276 va_start(ap
, format
);
277 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
282 if (config
->debug
< level
) return;
284 va_start(ap
, format
);
285 vsnprintf(message
, sizeof(message
), format
, ap
);
288 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
290 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
295 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
298 const uint8_t *d
= data
;
300 if (config
->debug
< level
) return;
302 // No support for _log_hex to syslog
305 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
306 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
308 for (i
= 0; i
< maxsize
; )
310 fprintf(log_stream
, "%4X: ", i
);
311 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
313 fprintf(log_stream
, "%02X ", d
[j
]);
315 fputs(": ", log_stream
);
318 for (; j
< i
+ 16; j
++)
320 fputs(" ", log_stream
);
322 fputs(": ", log_stream
);
325 fputs(" ", log_stream
);
326 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
328 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
329 fputc(d
[j
], log_stream
);
331 fputc('.', log_stream
);
334 fputs(" ", log_stream
);
338 fputs("\n", log_stream
);
342 setbuf(log_stream
, NULL
);
346 // update a counter, accumulating 2^32 wraps
347 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
349 uint32_t new = *counter
+ delta
;
356 // initialise the random generator
357 static void initrandom(char *source
)
359 static char path
[sizeof(config
->random_device
)] = "*undefined*";
361 // reinitialise only if we are forced to do so or if the config has changed
362 if (source
&& !strncmp(path
, source
, sizeof(path
)))
365 // close previous source, if any
374 snprintf(path
, sizeof(path
), "%s", source
);
378 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
380 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
381 path
, strerror(errno
));
386 // fill buffer with random data
387 void random_data(uint8_t *buf
, int len
)
394 n
= read(rand_fd
, buf
, len
);
395 if (n
>= len
) return;
400 LOG(0, 0, 0, "Error reading from random source: %s\n",
403 // fall back to rand()
411 // append missing data
413 // not using the low order bits from the prng stream
414 buf
[n
++] = (rand() >> 4) & 0xff;
419 // This adds it to the routing table, advertises it
420 // via BGP if enabled, and stuffs it into the
421 // 'sessionbyip' cache.
423 // 'ip' must be in _host_ order.
425 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
435 if (!prefixlen
) prefixlen
= 32;
437 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
439 memset(&req
, 0, sizeof(req
));
443 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
444 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
448 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
449 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
452 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
454 req
.rt
.rtm_family
= AF_INET
;
455 req
.rt
.rtm_dst_len
= prefixlen
;
456 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
457 req
.rt
.rtm_protocol
= 42;
458 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
459 req
.rt
.rtm_type
= RTN_UNICAST
;
461 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
463 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
467 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
470 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
471 fmtaddr(htonl(ip
), 0), prefixlen
,
472 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
474 if (netlink_send(&req
.nh
) < 0)
475 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
479 bgp_add_route(htonl(ip
), prefixlen
);
481 bgp_del_route(htonl(ip
), prefixlen
);
484 // Add/Remove the IPs to the 'sessionbyip' cache.
485 // Note that we add the zero address in the case of
486 // a network route. Roll on CIDR.
488 // Note that 's == 0' implies this is the address pool.
489 // We still cache it here, because it will pre-fill
490 // the malloc'ed tree.
494 if (!add
) // Are we deleting a route?
495 s
= 0; // Caching the session as '0' is the same as uncaching.
497 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
502 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
510 char ipv6addr
[INET6_ADDRSTRLEN
];
512 if (!config
->ipv6_prefix
.s6_addr
[0])
514 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
518 memset(&req
, 0, sizeof(req
));
522 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
523 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
527 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
528 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
531 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
533 req
.rt
.rtm_family
= AF_INET6
;
534 req
.rt
.rtm_dst_len
= prefixlen
;
535 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
536 req
.rt
.rtm_protocol
= 42;
537 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
538 req
.rt
.rtm_type
= RTN_UNICAST
;
540 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
541 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
543 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
545 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
547 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
550 if (netlink_send(&req
.nh
) < 0)
551 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
555 bgp_add_route6(ip
, prefixlen
);
557 bgp_del_route6(ip
, prefixlen
);
562 if (!add
) // Are we deleting a route?
563 s
= 0; // Caching the session as '0' is the same as uncaching.
565 cache_ipv6map(ip
, prefixlen
, s
);
572 // Set up netlink socket
573 static void initnetlink(void)
575 struct sockaddr_nl nladdr
;
577 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
580 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
584 memset(&nladdr
, 0, sizeof(nladdr
));
585 nladdr
.nl_family
= AF_NETLINK
;
586 nladdr
.nl_pid
= getpid();
588 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
590 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
595 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
597 struct sockaddr_nl nladdr
;
601 nh
->nlmsg_pid
= getpid();
602 nh
->nlmsg_seq
= ++nlseqnum
;
604 // set kernel address
605 memset(&nladdr
, 0, sizeof(nladdr
));
606 nladdr
.nl_family
= AF_NETLINK
;
608 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
609 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
611 return sendmsg(nlfd
, &msg
, 0);
614 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
616 struct sockaddr_nl nladdr
;
620 // set kernel address
621 memset(&nladdr
, 0, sizeof(nladdr
));
622 nladdr
.nl_family
= AF_NETLINK
;
624 iov
= (struct iovec
){ buf
, len
};
625 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
627 return recvmsg(nlfd
, &msg
, 0);
630 /* adapted from iproute2 */
631 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
633 int len
= RTA_LENGTH(alen
);
636 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
637 rta
->rta_type
= type
;
639 memcpy(RTA_DATA(rta
), data
, alen
);
640 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
643 // messages corresponding to different phases seq number
644 static char *tun_nl_phase_msg
[] = {
646 "getting tun interface index",
647 "setting tun interface parameters",
648 "setting tun IPv4 address",
649 "setting tun LL IPv6 address",
650 "setting tun global IPv6 address",
654 // Set up TUN interface
655 static void inittun(void)
659 memset(&ifr
, 0, sizeof(ifr
));
660 ifr
.ifr_flags
= IFF_TUN
;
662 tunfd
= open(TUNDEVICE
, O_RDWR
);
665 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
669 int flags
= fcntl(tunfd
, F_GETFL
, 0);
670 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
672 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
674 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
677 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
) - 1);
678 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
));
680 tunidx
= if_nametoindex(config
->tundevice
);
683 LOG(0, 0, 0, "Can't get tun interface index\n");
692 struct ifinfomsg ifinfo
;
693 struct ifaddrmsg ifaddr
;
695 char rtdata
[32]; // 32 should be enough
697 uint32_t txqlen
, mtu
;
700 memset(&req
, 0, sizeof(req
));
702 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
703 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
704 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
706 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
707 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
708 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
709 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
711 /* Bump up the qlen to deal with bursts from the network */
713 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
714 /* set MTU to modem MRU */
716 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
718 if (netlink_send(&req
.nh
) < 0)
721 memset(&req
, 0, sizeof(req
));
723 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
724 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
725 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
727 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
728 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
729 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
730 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
732 if (config
->bind_address
)
733 ip
= config
->bind_address
;
735 ip
= 0x01010101; // 1.1.1.1
736 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
738 if (netlink_send(&req
.nh
) < 0)
741 // Only setup IPv6 on the tun device if we have a configured prefix
742 if (config
->ipv6_prefix
.s6_addr
[0]) {
745 memset(&req
, 0, sizeof(req
));
747 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
748 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
749 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
751 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
752 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
753 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
754 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
756 // Link local address is FE80::1
757 memset(&ip6
, 0, sizeof(ip6
));
758 ip6
.s6_addr
[0] = 0xFE;
759 ip6
.s6_addr
[1] = 0x80;
761 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
763 if (netlink_send(&req
.nh
) < 0)
766 memset(&req
, 0, sizeof(req
));
768 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
769 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
770 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
772 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
773 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
774 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
775 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
777 // Global address is prefix::1
778 ip6
= config
->ipv6_prefix
;
780 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
782 if (netlink_send(&req
.nh
) < 0)
786 memset(&req
, 0, sizeof(req
));
788 req
.nh
.nlmsg_type
= NLMSG_DONE
;
789 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
791 if (netlink_send(&req
.nh
) < 0)
794 // if we get an error for seqnum < min_initok_nlseqnum,
795 // we must exit as initialization went wrong
796 if (config
->ipv6_prefix
.s6_addr
[0])
797 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
799 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
805 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
810 static void initudp(void)
813 struct sockaddr_in addr
;
816 memset(&addr
, 0, sizeof(addr
));
817 addr
.sin_family
= AF_INET
;
818 addr
.sin_port
= htons(L2TPPORT
);
819 addr
.sin_addr
.s_addr
= config
->bind_address
;
820 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
821 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
823 int flags
= fcntl(udpfd
, F_GETFL
, 0);
824 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
826 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
828 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
833 memset(&addr
, 0, sizeof(addr
));
834 addr
.sin_family
= AF_INET
;
835 addr
.sin_port
= htons(NSCTL_PORT
);
836 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
837 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
838 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
839 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
841 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
845 // Dynamic Authorization Extensions to RADIUS
846 memset(&addr
, 0, sizeof(addr
));
847 addr
.sin_family
= AF_INET
;
848 addr
.sin_port
= htons(config
->radius_dae_port
);
849 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
850 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
851 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
852 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
854 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
859 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
863 // Find session by IP, < 1 for not found
865 // Confusingly enough, this 'ip' must be
866 // in _network_ order. This being the common
867 // case when looking it up from IP packet headers.
869 // We actually use this cache for two things.
870 // #1. For used IP addresses, this maps to the
871 // session ID that it's used by.
872 // #2. For un-used IP addresses, this maps to the
873 // index into the pool table that contains that
877 static sessionidt
lookup_ipmap(in_addr_t ip
)
879 uint8_t *a
= (uint8_t *) &ip
;
880 union iphash
*h
= ip_hash
;
882 if (!(h
= h
[*a
++].idx
)) return 0;
883 if (!(h
= h
[*a
++].idx
)) return 0;
884 if (!(h
= h
[*a
++].idx
)) return 0;
889 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
891 struct ipv6radix
*curnode
;
894 char ipv6addr
[INET6_ADDRSTRLEN
];
896 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
900 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
902 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
907 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
908 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
915 sessionidt
sessionbyip(in_addr_t ip
)
917 sessionidt s
= lookup_ipmap(ip
);
920 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
926 sessionidt
sessionbyipv6(struct in6_addr ip
)
929 CSTAT(sessionbyipv6
);
931 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
932 (ip
.s6_addr
[0] == 0xFE &&
933 ip
.s6_addr
[1] == 0x80 &&
934 ip
.s6_addr16
[1] == 0 &&
935 ip
.s6_addr16
[2] == 0 &&
936 ip
.s6_addr16
[3] == 0)) {
937 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
939 s
= lookup_ipv6map(ip
);
942 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
949 // Take an IP address in HOST byte order and
950 // add it to the sessionid by IP cache.
952 // (It's actually cached in network order)
954 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
956 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
957 uint8_t *a
= (uint8_t *) &nip
;
958 union iphash
*h
= ip_hash
;
961 for (i
= 0; i
< 3; i
++)
963 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
972 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
975 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
976 // else a map to an ip pool index.
979 static void uncache_ipmap(in_addr_t ip
)
981 cache_ipmap(ip
, 0); // Assign it to the NULL session.
984 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
988 struct ipv6radix
*curnode
;
989 char ipv6addr
[INET6_ADDRSTRLEN
];
991 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
993 bytes
= prefixlen
>> 3;
996 if (curnode
->branch
== NULL
)
998 if (!(curnode
->branch
= calloc(256,
999 sizeof (struct ipv6radix
))))
1002 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1009 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1010 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1014 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1015 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1021 // CLI list to dump current ipcache.
1023 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1025 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1029 if (CLI_HELP_REQUESTED
)
1030 return CLI_HELP_NO_ARGS
;
1032 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1034 for (i
= 0; i
< 256; ++i
)
1040 for (j
= 0; j
< 256; ++j
)
1046 for (k
= 0; k
< 256; ++k
)
1052 for (l
= 0; l
< 256; ++l
)
1057 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1063 cli_print(cli
, "%d entries in cache", count
);
1068 // Find session by username, 0 for not found
1069 // walled garden users aren't authenticated, so the username is
1070 // reasonably useless. Ignore them to avoid incorrect actions
1072 // This is VERY inefficent. Don't call it often. :)
1074 sessionidt
sessionbyuser(char *username
)
1077 CSTAT(sessionbyuser
);
1079 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1081 if (!session
[s
].opened
)
1084 if (session
[s
].walled_garden
)
1085 continue; // Skip walled garden users.
1087 if (!strncmp(session
[s
].user
, username
, 128))
1091 return 0; // Not found.
1094 void send_garp(in_addr_t ip
)
1100 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1103 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1106 memset(&ifr
, 0, sizeof(ifr
));
1107 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1108 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1110 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1114 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1115 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1117 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1122 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1125 static sessiont
*sessiontbysessionidt(sessionidt s
)
1127 if (!s
|| s
>= MAXSESSION
) return NULL
;
1131 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1133 sessionidt val
= s
-session
;
1134 if (s
< session
|| val
>= MAXSESSION
) return 0;
1138 // actually send a control message for a specific tunnel
1139 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1141 struct sockaddr_in addr
;
1147 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1148 STAT(tunnel_tx_errors
);
1154 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1155 STAT(tunnel_tx_errors
);
1159 memset(&addr
, 0, sizeof(addr
));
1160 addr
.sin_family
= AF_INET
;
1161 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1162 addr
.sin_port
= htons(tunnel
[t
].port
);
1164 // sequence expected, if sequence in message
1165 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1167 // If this is a control message, deal with retries
1170 tunnel
[t
].last
= time_now
; // control message sent
1171 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1174 STAT(tunnel_retries
);
1175 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1179 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1181 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1182 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1183 STAT(tunnel_tx_errors
);
1187 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1188 STAT(tunnel_tx_packets
);
1189 INC_STAT(tunnel_tx_bytes
, l
);
1193 // Tiny helper function to write data to
1194 // the 'tun' device.
1196 int tun_write(uint8_t * data
, int size
)
1198 return write(tunfd
, data
, size
);
1201 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1202 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1204 int d
= (tcp
[12] >> 4) * 4;
1211 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1214 if (tcp
+ d
> buf
+ len
) // short?
1222 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1225 if (mss
+ 2 > data
) return; // short?
1229 if (*opts
== 0) return; // end of options
1230 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1233 opts
+= opts
[1]; // skip over option
1236 if (!mss
) return; // not found
1237 orig
= ntohs(*(uint16_t *) mss
);
1239 if (orig
<= MSS
) return; // mss OK
1241 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1242 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1243 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1244 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1247 *(int16_t *) mss
= htons(MSS
);
1249 // adjust checksum (see rfc1141)
1250 sum
= orig
+ (~MSS
& 0xffff);
1251 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1252 sum
= (sum
& 0xffff) + (sum
>> 16);
1253 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1256 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1260 // Skip the four extra bytes
1272 proto
= ntohs(*(uint16_t *) p
);
1280 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1281 return; // closing session, PPP not processed
1283 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1284 processipin(s
, t
, p
, l
);
1286 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1290 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1291 return; // closing session, PPP not processed
1294 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1295 processipv6in(s
, t
, p
, l
);
1297 else if (proto
== PPPIPCP
)
1299 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1300 processipcp(s
, t
, p
, l
);
1302 else if (proto
== PPPCCP
)
1304 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1305 processccp(s
, t
, p
, l
);
1309 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1313 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1315 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1316 sp
->cout_delta
+= len
;
1318 sp
->last_data
= time_now
;
1320 sess_local
[s
].cout
+= len
; // To send to master..
1321 sess_local
[s
].pout
++;
1324 // process outgoing (to tunnel) IP
1326 static void processipout(uint8_t *buf
, int len
)
1333 uint8_t *data
= buf
; // Keep a copy of the originals.
1336 uint8_t fragbuf
[MAXETHER
+ 20];
1338 CSTAT(processipout
);
1340 if (len
< MIN_IP_SIZE
)
1342 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1343 STAT(tun_rx_errors
);
1346 if (len
>= MAXETHER
)
1348 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1349 STAT(tun_rx_errors
);
1353 // Skip the tun header
1357 // Got an IP header now
1358 if (*(uint8_t *)(buf
) >> 4 != 4)
1360 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1364 ip
= *(uint32_t *)(buf
+ 16);
1365 if (!(s
= sessionbyip(ip
)))
1367 // Is this a packet for a session that doesn't exist?
1368 static int rate
= 0; // Number of ICMP packets we've sent this second.
1369 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1371 if (last
!= time_now
)
1377 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1379 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1380 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1381 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1386 t
= session
[s
].tunnel
;
1387 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1389 LOG(3, s
, t
, "Packet size more than session MRU\n");
1395 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1396 if (config
->max_packets
> 0)
1398 if (sess_local
[s
].last_packet_out
== TIME
)
1400 int max
= config
->max_packets
;
1402 // All packets for throttled sessions are handled by the
1403 // master, so further limit by using the throttle rate.
1404 // A bit of a kludge, since throttle rate is in kbps,
1405 // but should still be generous given our average DSL
1406 // packet size is 200 bytes: a limit of 28kbps equates
1407 // to around 180 packets per second.
1408 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1409 max
= sp
->throttle_out
;
1411 if (++sess_local
[s
].packets_out
> max
)
1413 sess_local
[s
].packets_dropped
++;
1419 if (sess_local
[s
].packets_dropped
)
1421 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1422 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1423 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1424 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1428 sess_local
[s
].last_packet_out
= TIME
;
1429 sess_local
[s
].packets_out
= 1;
1430 sess_local
[s
].packets_dropped
= 0;
1434 // run access-list if any
1435 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1438 // adjust MSS on SYN and SYN,ACK packets with options
1439 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1441 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1442 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1443 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1448 // Are we throttling this session?
1449 if (config
->cluster_iam_master
)
1450 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1452 master_throttle_packet(sp
->tbf_out
, data
, size
);
1456 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1458 // We are walled-gardening this
1459 master_garden_packet(s
, data
, size
);
1463 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1465 // Add on L2TP header
1466 bundleidt bid
= session
[s
].bundle
;
1467 bundlet
*b
= &bundle
[bid
];
1469 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1470 s
= b
->members
[b
->current_ses
];
1471 t
= session
[s
].tunnel
;
1473 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1474 if(len
> MINFRAGLEN
)
1476 // Partition the packet to "bundle[b].num_of_links" fragments
1477 uint32_t num_of_links
= b
->num_of_links
;
1478 uint32_t fraglen
= len
/ num_of_links
;
1479 fraglen
= (fraglen
> session
[s
].mru
? session
[s
].mru
: fraglen
);
1480 uint32_t last_fraglen
= fraglen
+ len
% num_of_links
;
1481 last_fraglen
= (last_fraglen
> session
[s
].mru
? len
% num_of_links
: last_fraglen
);
1482 uint32_t remain
= len
;
1484 // send the first packet
1485 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1487 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1489 update_session_out_stat(s
, sp
, fraglen
);
1491 while (remain
> last_fraglen
)
1493 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1494 s
= b
->members
[b
->current_ses
];
1495 t
= session
[s
].tunnel
;
1497 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1498 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1500 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1501 update_session_out_stat(s
, sp
, fraglen
);
1504 // send the last fragment
1505 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1506 s
= b
->members
[b
->current_ses
];
1507 t
= session
[s
].tunnel
;
1509 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1510 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1512 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1513 update_session_out_stat(s
, sp
, remain
);
1514 if (remain
!= last_fraglen
)
1515 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1518 // Send it as one frame
1519 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1521 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1522 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1523 update_session_out_stat(s
, sp
, len
);
1528 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1530 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1531 update_session_out_stat(s
, sp
, len
);
1534 // Snooping this session, send it to intercept box
1535 if (sp
->snoop_ip
&& sp
->snoop_port
)
1536 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1541 // process outgoing (to tunnel) IPv6
1543 static void processipv6out(uint8_t * buf
, int len
)
1549 struct in6_addr ip6
;
1551 uint8_t *data
= buf
; // Keep a copy of the originals.
1554 uint8_t b
[MAXETHER
+ 20];
1556 CSTAT(processipv6out
);
1558 if (len
< MIN_IP_SIZE
)
1560 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1561 STAT(tunnel_tx_errors
);
1564 if (len
>= MAXETHER
)
1566 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1567 STAT(tunnel_tx_errors
);
1571 // Skip the tun header
1575 // Got an IP header now
1576 if (*(uint8_t *)(buf
) >> 4 != 6)
1578 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1582 ip6
= *(struct in6_addr
*)(buf
+24);
1583 s
= sessionbyipv6(ip6
);
1587 ip
= *(uint32_t *)(buf
+ 32);
1588 s
= sessionbyip(ip
);
1593 // Is this a packet for a session that doesn't exist?
1594 static int rate
= 0; // Number of ICMP packets we've sent this second.
1595 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1597 if (last
!= time_now
)
1603 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1605 // FIXME: Should send icmp6 host unreachable
1609 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1611 bundleidt bid
= session
[s
].bundle
;
1612 bundlet
*b
= &bundle
[bid
];
1614 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1615 s
= b
->members
[b
->current_ses
];
1616 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1618 t
= session
[s
].tunnel
;
1620 sp
->last_data
= time_now
;
1622 // FIXME: add DoS prevention/filters?
1626 // Are we throttling this session?
1627 if (config
->cluster_iam_master
)
1628 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1630 master_throttle_packet(sp
->tbf_out
, data
, size
);
1633 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1635 // We are walled-gardening this
1636 master_garden_packet(s
, data
, size
);
1640 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1642 // Add on L2TP header
1644 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1646 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1649 // Snooping this session, send it to intercept box
1650 if (sp
->snoop_ip
&& sp
->snoop_port
)
1651 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1653 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1654 sp
->cout_delta
+= len
;
1658 sess_local
[s
].cout
+= len
; // To send to master..
1659 sess_local
[s
].pout
++;
1663 // Helper routine for the TBF filters.
1664 // Used to send queued data in to the user!
1666 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1671 uint8_t b
[MAXETHER
+ 20];
1673 if (len
< 0 || len
> MAXETHER
)
1675 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1679 // Skip the tun header
1686 t
= session
[s
].tunnel
;
1689 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1691 // Add on L2TP header
1693 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1695 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1698 // Snooping this session.
1699 if (sp
->snoop_ip
&& sp
->snoop_port
)
1700 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1702 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1703 sp
->cout_delta
+= len
;
1707 sess_local
[s
].cout
+= len
; // To send to master..
1708 sess_local
[s
].pout
++;
1711 // add an AVP (16 bit)
1712 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1714 uint16_t l
= (m
? 0x8008 : 0x0008);
1715 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1716 c
->buf16
[c
->length
/2 + 1] = htons(0);
1717 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1718 c
->buf16
[c
->length
/2 + 3] = htons(val
);
1722 // add an AVP (32 bit)
1723 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1725 uint16_t l
= (m
? 0x800A : 0x000A);
1726 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1727 c
->buf16
[c
->length
/2 + 1] = htons(0);
1728 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1729 *(uint32_t *) &c
->buf
[c
->length
+ 6] = htonl(val
);
1733 // add an AVP (string)
1734 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1736 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1737 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1738 c
->buf16
[c
->length
/2 + 1] = htons(0);
1739 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1740 memcpy(&c
->buf
[c
->length
+ 6], val
, strlen(val
));
1741 c
->length
+= 6 + strlen(val
);
1745 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1747 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1748 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1749 c
->buf16
[c
->length
/2 + 1] = htons(0);
1750 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1751 memcpy(&c
->buf
[c
->length
+ 6], val
, len
);
1752 c
->length
+= 6 + len
;
1755 // new control connection
1756 static controlt
*controlnew(uint16_t mtype
)
1760 c
= malloc(sizeof(controlt
));
1764 controlfree
= c
->next
;
1768 c
->buf16
[0] = htons(0xC802); // flags/ver
1770 control16(c
, 0, mtype
, 1);
1774 // send zero block if nothing is waiting
1776 static void controlnull(tunnelidt t
)
1779 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1782 buf
[0] = htons(0xC802); // flags/ver
1783 buf
[1] = htons(12); // length
1784 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1785 buf
[3] = htons(0); // session
1786 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1787 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1788 tunnelsend((uint8_t *)buf
, 12, t
);
1791 // add a control message to a tunnel, and send if within window
1792 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1794 c
->buf16
[1] = htons(c
->length
); // length
1795 c
->buf16
[2] = htons(tunnel
[t
].far
); // tunnel
1796 c
->buf16
[3] = htons(far
); // session
1797 c
->buf16
[4] = htons(tunnel
[t
].ns
); // sequence
1798 tunnel
[t
].ns
++; // advance sequence
1799 // link in message in to queue
1800 if (tunnel
[t
].controlc
)
1801 tunnel
[t
].controle
->next
= c
;
1803 tunnel
[t
].controls
= c
;
1805 tunnel
[t
].controle
= c
;
1806 tunnel
[t
].controlc
++;
1808 // send now if space in window
1809 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1811 tunnel
[t
].try = 0; // first send
1812 tunnelsend(c
->buf
, c
->length
, t
);
1817 // Throttle or Unthrottle a session
1819 // Throttle the data from/to through a session to no more than
1820 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1823 // If either value is -1, the current value is retained for that
1826 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1828 if (!session
[s
].opened
)
1829 return; // No-one home.
1831 if (!*session
[s
].user
)
1832 return; // User not logged in
1836 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1837 if (session
[s
].tbf_in
)
1838 free_tbf(session
[s
].tbf_in
);
1841 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1843 session
[s
].tbf_in
= 0;
1845 session
[s
].throttle_in
= rate_in
;
1850 int bytes
= rate_out
* 1024 / 8;
1851 if (session
[s
].tbf_out
)
1852 free_tbf(session
[s
].tbf_out
);
1855 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1857 session
[s
].tbf_out
= 0;
1859 session
[s
].throttle_out
= rate_out
;
1863 // add/remove filters from session (-1 = no change)
1864 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1866 if (!session
[s
].opened
)
1867 return; // No-one home.
1869 if (!*session
[s
].user
)
1870 return; // User not logged in
1873 if (filter_in
> MAXFILTER
) filter_in
= -1;
1874 if (filter_out
> MAXFILTER
) filter_out
= -1;
1875 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1876 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1880 if (session
[s
].filter_in
)
1881 ip_filters
[session
[s
].filter_in
- 1].used
--;
1884 ip_filters
[filter_in
- 1].used
++;
1886 session
[s
].filter_in
= filter_in
;
1889 if (filter_out
>= 0)
1891 if (session
[s
].filter_out
)
1892 ip_filters
[session
[s
].filter_out
- 1].used
--;
1895 ip_filters
[filter_out
- 1].used
++;
1897 session
[s
].filter_out
= filter_out
;
1901 // start tidy shutdown of session
1902 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1904 int walled_garden
= session
[s
].walled_garden
;
1905 bundleidt b
= session
[s
].bundle
;
1906 //delete routes only for last session in bundle (in case of MPPP)
1907 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1909 CSTAT(sessionshutdown
);
1911 if (!session
[s
].opened
)
1913 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1914 return; // not a live session
1917 if (!session
[s
].die
)
1919 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1920 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1921 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1922 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1925 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1927 // RADIUS Stop message
1928 uint16_t r
= radiusnew(s
);
1931 // stop, if not already trying
1932 if (radius
[r
].state
!= RADIUSSTOP
)
1934 radius
[r
].term_cause
= term_cause
;
1935 radius
[r
].term_msg
= reason
;
1936 radiussend(r
, RADIUSSTOP
);
1940 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1942 // Save counters to dump to accounting file
1943 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1944 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1948 { // IP allocated, clear and unroute
1951 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1953 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
1954 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
1957 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
1958 session
[s
].route
[r
].ip
= 0;
1961 if (session
[s
].ip_pool_index
== -1) // static ip
1963 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1969 // unroute IPv6, if setup
1970 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
1971 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1975 // This session was part of a bundle
1976 bundle
[b
].num_of_links
--;
1977 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
1978 if(bundle
[b
].num_of_links
== 0)
1981 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
1985 // Adjust the members array to accomodate the new change
1986 uint8_t mem_num
= 0;
1987 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
1988 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
1991 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
1992 if(bundle
[b
].members
[ml
] == s
)
1997 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
1998 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2001 cluster_send_bundle(b
);
2005 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2006 throttle_session(s
, 0, 0);
2010 controlt
*c
= controlnew(14); // sending CDN
2014 buf
[0] = htons(cdn_result
);
2015 buf
[1] = htons(cdn_error
);
2016 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2019 control16(c
, 1, cdn_result
, 1);
2021 control16(c
, 14, s
, 1); // assigned session (our end)
2022 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2025 // update filter refcounts
2026 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2027 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2030 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2031 sess_local
[s
].lcp
.restart
= 0;
2032 sess_local
[s
].ipcp
.restart
= 0;
2033 sess_local
[s
].ipv6cp
.restart
= 0;
2034 sess_local
[s
].ccp
.restart
= 0;
2036 cluster_send_session(s
);
2039 void sendipcp(sessionidt s
, tunnelidt t
)
2041 uint8_t buf
[MAXETHER
];
2045 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2047 if (!session
[s
].unique_id
)
2049 if (!++last_id
) ++last_id
; // skip zero
2050 session
[s
].unique_id
= last_id
;
2053 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2057 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2058 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2059 q
[4] = 3; // ip address option
2060 q
[5] = 6; // option length
2061 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2062 config
->bind_address
? config
->bind_address
:
2063 my_address
; // send my IP
2065 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2066 restart_timer(s
, ipcp
);
2069 void sendipv6cp(sessionidt s
, tunnelidt t
)
2071 uint8_t buf
[MAXETHER
];
2075 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2077 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2081 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2082 // only send one type
2084 *(uint16_t *) (q
+ 2) = htons(14);
2085 q
[4] = 1; // interface identifier option
2086 q
[5] = 10; // option length
2087 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2088 *(uint32_t *) (q
+ 10) = 0;
2091 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2092 restart_timer(s
, ipv6cp
);
2095 static void sessionclear(sessionidt s
)
2097 memset(&session
[s
], 0, sizeof(session
[s
]));
2098 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2099 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2101 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2102 session
[s
].next
= sessionfree
;
2106 // kill a session now
2107 void sessionkill(sessionidt s
, char *reason
)
2111 if (!session
[s
].opened
) // not alive
2114 if (session
[s
].next
)
2116 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2120 if (!session
[s
].die
)
2121 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2123 if (sess_local
[s
].radius
)
2124 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2126 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2128 cluster_send_session(s
);
2131 static void tunnelclear(tunnelidt t
)
2134 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2135 tunnel
[t
].state
= TUNNELFREE
;
2138 static void bundleclear(bundleidt b
)
2141 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2142 bundle
[b
].state
= BUNDLEFREE
;
2145 // kill a tunnel now
2146 static void tunnelkill(tunnelidt t
, char *reason
)
2153 tunnel
[t
].state
= TUNNELDIE
;
2155 // free control messages
2156 while ((c
= tunnel
[t
].controls
))
2158 controlt
* n
= c
->next
;
2159 tunnel
[t
].controls
= n
;
2160 tunnel
[t
].controlc
--;
2161 c
->next
= controlfree
;
2165 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2166 if (session
[s
].tunnel
== t
)
2167 sessionkill(s
, reason
);
2171 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2172 cli_tunnel_actions
[t
].action
= 0;
2173 cluster_send_tunnel(t
);
2176 // shut down a tunnel cleanly
2177 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2181 CSTAT(tunnelshutdown
);
2183 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2185 // never set up, can immediately kill
2186 tunnelkill(t
, reason
);
2189 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2192 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2193 if (session
[s
].tunnel
== t
)
2194 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2196 tunnel
[t
].state
= TUNNELDIE
;
2197 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2198 cluster_send_tunnel(t
);
2199 // TBA - should we wait for sessions to stop?
2202 controlt
*c
= controlnew(4); // sending StopCCN
2207 buf
[0] = htons(result
);
2208 buf
[1] = htons(error
);
2211 int m
= strlen(msg
);
2212 if (m
+ 4 > sizeof(buf
))
2213 m
= sizeof(buf
) - 4;
2215 memcpy(buf
+2, msg
, m
);
2219 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2222 control16(c
, 1, result
, 1);
2224 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2225 controladd(c
, 0, t
); // send the message
2229 // read and process packet on tunnel (UDP)
2230 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2232 uint8_t *chapresponse
= NULL
;
2233 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2234 uint8_t *p
= buf
+ 2;
2241 LOG_HEX(5, "UDP Data", buf
, len
);
2242 STAT(tunnel_rx_packets
);
2243 INC_STAT(tunnel_rx_bytes
, len
);
2246 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2247 STAT(tunnel_rx_errors
);
2250 if ((buf
[1] & 0x0F) != 2)
2252 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2253 STAT(tunnel_rx_errors
);
2258 l
= ntohs(*(uint16_t *) p
);
2261 t
= ntohs(*(uint16_t *) p
);
2263 s
= ntohs(*(uint16_t *) p
);
2265 if (s
>= MAXSESSION
)
2267 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2268 STAT(tunnel_rx_errors
);
2273 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2274 STAT(tunnel_rx_errors
);
2279 ns
= ntohs(*(uint16_t *) p
);
2281 nr
= ntohs(*(uint16_t *) p
);
2286 uint16_t o
= ntohs(*(uint16_t *) p
);
2291 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2292 STAT(tunnel_rx_errors
);
2297 // used to time out old tunnels
2298 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2299 tunnel
[t
].lastrec
= time_now
;
2303 uint16_t message
= 0xFFFF; // message type
2305 uint8_t mandatory
= 0;
2306 uint16_t asession
= 0; // assigned session
2307 uint32_t amagic
= 0; // magic number
2308 uint8_t aflags
= 0; // flags from last LCF
2309 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2310 char called
[MAXTEL
] = ""; // called number
2311 char calling
[MAXTEL
] = ""; // calling number
2313 if (!config
->cluster_iam_master
)
2315 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2319 // control messages must have bits 0x80|0x40|0x08
2320 // (type, length and sequence) set, and bits 0x02|0x01
2321 // (offset and priority) clear
2322 if ((*buf
& 0xCB) != 0xC8)
2324 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2325 STAT(tunnel_rx_errors
);
2329 // check for duplicate tunnel open message
2335 // Is this a duplicate of the first packet? (SCCRQ)
2337 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2339 if (tunnel
[i
].state
!= TUNNELOPENING
||
2340 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2341 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2344 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2349 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2350 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2352 // if no tunnel specified, assign one
2355 if (!(t
= new_tunnel()))
2357 LOG(1, 0, 0, "No more tunnels\n");
2358 STAT(tunnel_overflow
);
2362 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2363 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2364 tunnel
[t
].window
= 4; // default window
2365 STAT(tunnel_created
);
2366 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2367 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2370 // If the 'ns' just received is not the 'nr' we're
2371 // expecting, just send an ack and drop it.
2373 // if 'ns' is less, then we got a retransmitted packet.
2374 // if 'ns' is greater than missed a packet. Either way
2375 // we should ignore it.
2376 if (ns
!= tunnel
[t
].nr
)
2378 // is this the sequence we were expecting?
2379 STAT(tunnel_rx_errors
);
2380 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2381 t
, ns
, tunnel
[t
].nr
);
2383 if (l
) // Is this not a ZLB?
2388 // check sequence of this message
2390 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2391 // some to clear maybe?
2392 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2394 controlt
*c
= tunnel
[t
].controls
;
2395 tunnel
[t
].controls
= c
->next
;
2396 tunnel
[t
].controlc
--;
2397 c
->next
= controlfree
;
2400 tunnel
[t
].try = 0; // we have progress
2403 // receiver advance (do here so quoted correctly in any sends below)
2404 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2405 if (skip
< 0) skip
= 0;
2406 if (skip
< tunnel
[t
].controlc
)
2408 // some control packets can now be sent that were previous stuck out of window
2409 int tosend
= tunnel
[t
].window
- skip
;
2410 controlt
*c
= tunnel
[t
].controls
;
2418 tunnel
[t
].try = 0; // first send
2419 tunnelsend(c
->buf
, c
->length
, t
);
2424 if (!tunnel
[t
].controlc
)
2425 tunnel
[t
].retry
= 0; // caught up
2428 { // if not a null message
2433 // Default disconnect cause/message on receipt of CDN. Set to
2434 // more specific value from attribute 1 (result code) or 46
2435 // (disconnect cause) if present below.
2436 int disc_cause_set
= 0;
2437 int disc_cause
= TERM_NAS_REQUEST
;
2438 char const *disc_reason
= "Closed (Received CDN).";
2441 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2443 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2450 LOG(1, s
, t
, "Invalid length in AVP\n");
2451 STAT(tunnel_rx_errors
);
2456 if (flags
& 0x3C) // reserved bits, should be clear
2458 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2460 result
= 2; // general error
2461 error
= 3; // reserved field non-zero
2466 if (*(uint16_t *) (b
))
2468 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2470 result
= 2; // general error
2471 error
= 6; // generic vendor-specific error
2472 msg
= "unsupported vendor-specific";
2476 mtype
= ntohs(*(uint16_t *) (b
));
2484 // handle hidden AVPs
2485 if (!*config
->l2tp_secret
)
2487 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2489 result
= 2; // general error
2490 error
= 6; // generic vendor-specific error
2491 msg
= "secret not specified";
2494 if (!session
[s
].random_vector_length
)
2496 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2498 result
= 2; // general error
2499 error
= 6; // generic
2500 msg
= "no random vector";
2505 LOG(2, s
, t
, "Short hidden AVP.\n");
2507 result
= 2; // general error
2508 error
= 2; // length is wrong
2514 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2516 orig_len
= ntohs(*(uint16_t *) b
);
2517 if (orig_len
> n
+ 2)
2519 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2523 result
= 2; // general error
2524 error
= 2; // length is wrong
2533 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2534 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2538 case 0: // message type
2539 message
= ntohs(*(uint16_t *) b
);
2540 mandatory
= flags
& 0x80;
2541 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2543 case 1: // result code
2545 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2546 char const *resdesc
= "(unknown)";
2547 char const *errdesc
= NULL
;
2552 resdesc
= l2tp_stopccn_result_code(rescode
);
2553 cause
= TERM_LOST_SERVICE
;
2555 else if (message
== 14)
2557 resdesc
= l2tp_cdn_result_code(rescode
);
2559 cause
= TERM_LOST_CARRIER
;
2561 cause
= TERM_ADMIN_RESET
;
2564 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2567 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2568 errdesc
= l2tp_error_code(errcode
);
2569 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2572 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2574 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2576 disc_cause_set
= mtype
;
2577 disc_reason
= errdesc
? errdesc
: resdesc
;
2584 case 2: // protocol version
2586 version
= ntohs(*(uint16_t *) (b
));
2587 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2588 if (version
&& version
!= 0x0100)
2589 { // allow 0.0 and 1.0
2590 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2592 result
= 5; // unspported protocol version
2593 error
= 0x0100; // supported version
2599 case 3: // framing capabilities
2601 case 4: // bearer capabilities
2603 case 5: // tie breaker
2604 // We never open tunnels, so we don't care about tie breakers
2606 case 6: // firmware revision
2608 case 7: // host name
2609 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2610 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2611 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2612 // TBA - to send to RADIUS
2614 case 8: // vendor name
2615 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2616 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2617 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2619 case 9: // assigned tunnel
2620 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2621 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2623 case 10: // rx window
2624 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2625 if (!tunnel
[t
].window
)
2626 tunnel
[t
].window
= 1; // window of 0 is silly
2627 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2629 case 11: // Challenge
2631 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2632 build_chap_response(b
, 2, n
, &chapresponse
);
2635 case 13: // Response
2636 // Why did they send a response? We never challenge.
2637 LOG(2, s
, t
, " received unexpected challenge response\n");
2640 case 14: // assigned session
2641 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2642 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2644 case 15: // call serial number
2645 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2647 case 18: // bearer type
2648 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2651 case 19: // framing type
2652 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2655 case 21: // called number
2656 memset(called
, 0, sizeof(called
));
2657 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2658 LOG(4, s
, t
, " Called <%s>\n", called
);
2660 case 22: // calling number
2661 memset(calling
, 0, sizeof(calling
));
2662 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2663 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2667 case 24: // tx connect speed
2670 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2674 // AS5300s send connect speed as a string
2676 memset(tmp
, 0, sizeof(tmp
));
2677 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2678 session
[s
].tx_connect_speed
= atol(tmp
);
2680 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2682 case 38: // rx connect speed
2685 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2689 // AS5300s send connect speed as a string
2691 memset(tmp
, 0, sizeof(tmp
));
2692 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2693 session
[s
].rx_connect_speed
= atol(tmp
);
2695 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2697 case 25: // Physical Channel ID
2699 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2700 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2703 case 29: // Proxy Authentication Type
2705 uint16_t atype
= ntohs(*(uint16_t *)b
);
2706 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2709 case 30: // Proxy Authentication Name
2712 memset(authname
, 0, sizeof(authname
));
2713 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2714 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2718 case 31: // Proxy Authentication Challenge
2720 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2723 case 32: // Proxy Authentication ID
2725 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2726 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2729 case 33: // Proxy Authentication Response
2730 LOG(4, s
, t
, " Proxy Auth Response\n");
2732 case 27: // last sent lcp
2733 { // find magic number
2734 uint8_t *p
= b
, *e
= p
+ n
;
2735 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2737 if (*p
== 5 && p
[1] == 6) // Magic-Number
2738 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2739 else if (*p
== 7) // Protocol-Field-Compression
2740 aflags
|= SESSION_PFC
;
2741 else if (*p
== 8) // Address-and-Control-Field-Compression
2742 aflags
|= SESSION_ACFC
;
2747 case 28: // last recv lcp confreq
2749 case 26: // Initial Received LCP CONFREQ
2751 case 39: // seq required - we control it as an LNS anyway...
2753 case 36: // Random Vector
2754 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2755 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2756 if (n
> sizeof(session
[s
].random_vector
))
2757 n
= sizeof(session
[s
].random_vector
);
2758 memcpy(session
[s
].random_vector
, b
, n
);
2759 session
[s
].random_vector_length
= n
;
2761 case 46: // ppp disconnect cause
2764 uint16_t code
= ntohs(*(uint16_t *) b
);
2765 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2766 uint8_t dir
= *(b
+ 4);
2768 LOG(4, s
, t
, " PPP disconnect cause "
2769 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2770 code
, proto
, dir
, n
- 5, b
+ 5);
2772 disc_cause_set
= mtype
;
2776 case 1: // admin disconnect
2777 disc_cause
= TERM_ADMIN_RESET
;
2778 disc_reason
= "Administrative disconnect";
2780 case 3: // lcp terminate
2781 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2782 disc_cause
= TERM_USER_REQUEST
;
2783 disc_reason
= "Normal disconnection";
2785 case 4: // compulsory encryption unavailable
2786 if (dir
!= 1) break; // 1=refused by peer, 2=local
2787 disc_cause
= TERM_USER_ERROR
;
2788 disc_reason
= "Compulsory encryption refused";
2790 case 5: // lcp: fsm timeout
2791 disc_cause
= TERM_PORT_ERROR
;
2792 disc_reason
= "LCP: FSM timeout";
2794 case 6: // lcp: no recognisable lcp packets received
2795 disc_cause
= TERM_PORT_ERROR
;
2796 disc_reason
= "LCP: no recognisable LCP packets";
2798 case 7: // lcp: magic-no error (possibly looped back)
2799 disc_cause
= TERM_PORT_ERROR
;
2800 disc_reason
= "LCP: magic-no error (possible loop)";
2802 case 8: // lcp: echo request timeout
2803 disc_cause
= TERM_PORT_ERROR
;
2804 disc_reason
= "LCP: echo request timeout";
2806 case 13: // auth: fsm timeout
2807 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2808 disc_reason
= "Authentication: FSM timeout";
2810 case 15: // auth: unacceptable auth protocol
2811 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2812 disc_reason
= "Unacceptable authentication protocol";
2814 case 16: // auth: authentication failed
2815 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2816 disc_reason
= "Authentication failed";
2818 case 17: // ncp: fsm timeout
2819 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2820 disc_reason
= "NCP: FSM timeout";
2822 case 18: // ncp: no ncps available
2823 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2824 disc_reason
= "NCP: no NCPs available";
2826 case 19: // ncp: failure to converge on acceptable address
2827 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2828 disc_reason
= (dir
== 1)
2829 ? "NCP: too many Configure-Naks received from peer"
2830 : "NCP: too many Configure-Naks sent to peer";
2832 case 20: // ncp: user not permitted to use any address
2833 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2834 disc_reason
= (dir
== 1)
2835 ? "NCP: local link address not acceptable to peer"
2836 : "NCP: remote link address not acceptable";
2843 static char e
[] = "unknown AVP 0xXXXX";
2844 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2846 result
= 2; // general error
2847 error
= 8; // unknown mandatory AVP
2848 sprintf((msg
= e
) + 14, "%04x", mtype
);
2855 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2859 case 1: // SCCRQ - Start Control Connection Request
2860 tunnel
[t
].state
= TUNNELOPENING
;
2861 if (main_quit
!= QUIT_SHUTDOWN
)
2863 controlt
*c
= controlnew(2); // sending SCCRP
2864 control16(c
, 2, version
, 1); // protocol version
2865 control32(c
, 3, 3, 1); // framing
2866 controls(c
, 7, hostname
, 1); // host name
2867 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2868 control16(c
, 9, t
, 1); // assigned tunnel
2869 controladd(c
, 0, t
); // send the resply
2873 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2877 tunnel
[t
].state
= TUNNELOPEN
;
2878 tunnel
[t
].lastrec
= time_now
;
2881 tunnel
[t
].state
= TUNNELOPEN
;
2882 tunnel
[t
].lastrec
= time_now
;
2883 controlnull(t
); // ack
2886 controlnull(t
); // ack
2887 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2890 controlnull(t
); // simply ACK
2902 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2904 controlt
*c
= controlnew(11); // ICRP
2907 sessionfree
= session
[s
].next
;
2908 memset(&session
[s
], 0, sizeof(session
[s
]));
2910 if (s
> config
->cluster_highest_sessionid
)
2911 config
->cluster_highest_sessionid
= s
;
2913 session
[s
].opened
= time_now
;
2914 session
[s
].tunnel
= t
;
2915 session
[s
].far
= asession
;
2916 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2917 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2918 control16(c
, 14, s
, 1); // assigned session
2919 controladd(c
, asession
, t
); // send the reply
2921 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2922 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2924 session
[s
].ppp
.phase
= Establish
;
2925 session
[s
].ppp
.lcp
= Starting
;
2927 STAT(session_created
);
2932 controlt
*c
= controlnew(14); // CDN
2935 STAT(session_overflow
);
2936 LOG(1, 0, t
, "No free sessions\n");
2937 control16(c
, 1, 4, 0); // temporary lack of resources
2940 control16(c
, 1, 2, 7); // shutting down, try another
2942 controladd(c
, asession
, t
); // send the message
2949 if (amagic
== 0) amagic
= time_now
;
2950 session
[s
].magic
= amagic
; // set magic number
2951 session
[s
].flags
= aflags
; // set flags received
2952 session
[s
].mru
= PPPoE_MRU
; // default
2953 controlnull(t
); // ack
2956 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
2957 sess_local
[s
].ppp_mru
= MRU
;
2959 // Set multilink options before sending initial LCP packet
2960 sess_local
[s
].mp_mrru
= 1614;
2961 sess_local
[s
].mp_epdis
= ntohl(config
->bind_address
? config
->bind_address
: my_address
);
2964 change_state(s
, lcp
, RequestSent
);
2968 controlnull(t
); // ack
2969 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
2972 LOG(1, s
, t
, "Missing message type\n");
2975 STAT(tunnel_rx_errors
);
2977 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2979 LOG(1, s
, t
, "Unknown message type %u\n", message
);
2982 if (chapresponse
) free(chapresponse
);
2983 cluster_send_tunnel(t
);
2987 LOG(4, s
, t
, " Got a ZLB ack\n");
2994 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
2995 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
2996 { // HDLC address header, discard
3002 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3003 STAT(tunnel_rx_errors
);
3013 proto
= ntohs(*(uint16_t *) p
);
3018 if (s
&& !session
[s
].opened
) // Is something wrong??
3020 if (!config
->cluster_iam_master
)
3022 // Pass it off to the master to deal with..
3023 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3028 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3029 STAT(tunnel_rx_errors
);
3033 if (proto
== PPPPAP
)
3035 session
[s
].last_packet
= time_now
;
3036 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3037 processpap(s
, t
, p
, l
);
3039 else if (proto
== PPPCHAP
)
3041 session
[s
].last_packet
= time_now
;
3042 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3043 processchap(s
, t
, p
, l
);
3045 else if (proto
== PPPLCP
)
3047 session
[s
].last_packet
= time_now
;
3048 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3049 processlcp(s
, t
, p
, l
);
3051 else if (proto
== PPPIPCP
)
3053 session
[s
].last_packet
= time_now
;
3054 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3055 processipcp(s
, t
, p
, l
);
3057 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3059 session
[s
].last_packet
= time_now
;
3060 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3061 processipv6cp(s
, t
, p
, l
);
3063 else if (proto
== PPPCCP
)
3065 session
[s
].last_packet
= time_now
;
3066 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3067 processccp(s
, t
, p
, l
);
3069 else if (proto
== PPPIP
)
3073 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3074 return; // closing session, PPP not processed
3077 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3078 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3080 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3084 processipin(s
, t
, p
, l
);
3086 else if (proto
== PPPMP
)
3090 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3091 return; // closing session, PPP not processed
3094 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3095 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3097 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3101 processmpin(s
, t
, p
, l
);
3103 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3107 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3108 return; // closing session, PPP not processed
3111 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3112 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3114 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3118 processipv6in(s
, t
, p
, l
);
3120 else if (session
[s
].ppp
.lcp
== Opened
)
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 protoreject(s
, t
, p
, l
, proto
);
3128 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3129 proto
, ppp_state(session
[s
].ppp
.lcp
));
3134 // read and process packet on tun
3135 static void processtun(uint8_t * buf
, int len
)
3137 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3138 STAT(tun_rx_packets
);
3139 INC_STAT(tun_rx_bytes
, len
);
3147 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3148 STAT(tun_rx_errors
);
3152 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3153 processipout(buf
, len
);
3154 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3155 && config
->ipv6_prefix
.s6_addr
[0])
3156 processipv6out(buf
, len
);
3161 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3162 // that we look at the whole of the tunnel, radius and session tables
3164 static void regular_cleanups(double period
)
3166 // Next tunnel, radius and session to check for actions on.
3167 static tunnelidt t
= 0;
3169 static sessionidt s
= 0;
3182 // divide up tables into slices based on the last run
3183 t_slice
= config
->cluster_highest_tunnelid
* period
;
3184 r_slice
= (MAXRADIUS
- 1) * period
;
3185 s_slice
= config
->cluster_highest_sessionid
* period
;
3189 else if (t_slice
> config
->cluster_highest_tunnelid
)
3190 t_slice
= config
->cluster_highest_tunnelid
;
3194 else if (r_slice
> (MAXRADIUS
- 1))
3195 r_slice
= MAXRADIUS
- 1;
3199 else if (s_slice
> config
->cluster_highest_sessionid
)
3200 s_slice
= config
->cluster_highest_sessionid
;
3202 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3204 for (i
= 0; i
< t_slice
; i
++)
3207 if (t
> config
->cluster_highest_tunnelid
)
3210 // check for expired tunnels
3211 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3213 STAT(tunnel_timeout
);
3214 tunnelkill(t
, "Expired");
3218 // check for message resend
3219 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3221 // resend pending messages as timeout on reply
3222 if (tunnel
[t
].retry
<= TIME
)
3224 controlt
*c
= tunnel
[t
].controls
;
3225 uint16_t w
= tunnel
[t
].window
;
3226 tunnel
[t
].try++; // another try
3227 if (tunnel
[t
].try > 5)
3228 tunnelkill(t
, "Timeout on control message"); // game over
3232 tunnelsend(c
->buf
, c
->length
, t
);
3240 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3242 controlt
*c
= controlnew(6); // sending HELLO
3243 controladd(c
, 0, t
); // send the message
3244 LOG(3, 0, t
, "Sending HELLO message\n");
3248 // Check for tunnel changes requested from the CLI
3249 if ((a
= cli_tunnel_actions
[t
].action
))
3251 cli_tunnel_actions
[t
].action
= 0;
3252 if (a
& CLI_TUN_KILL
)
3254 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3255 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3261 for (i
= 0; i
< r_slice
; i
++)
3267 if (!radius
[r
].state
)
3270 if (radius
[r
].retry
<= TIME
)
3277 for (i
= 0; i
< s_slice
; i
++)
3280 if (s
> config
->cluster_highest_sessionid
)
3283 if (!session
[s
].opened
) // Session isn't in use
3286 // check for expired sessions
3289 if (session
[s
].die
<= TIME
)
3291 sessionkill(s
, "Expired");
3298 if (sess_local
[s
].lcp
.restart
<= time_now
)
3300 int next_state
= session
[s
].ppp
.lcp
;
3301 switch (session
[s
].ppp
.lcp
)
3305 next_state
= RequestSent
;
3308 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3310 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3311 sendlcp(s
, session
[s
].tunnel
);
3312 change_state(s
, lcp
, next_state
);
3316 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3317 STAT(session_timeout
);
3327 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3329 int next_state
= session
[s
].ppp
.ipcp
;
3330 switch (session
[s
].ppp
.ipcp
)
3334 next_state
= RequestSent
;
3337 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3339 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3340 sendipcp(s
, session
[s
].tunnel
);
3341 change_state(s
, ipcp
, next_state
);
3345 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3346 STAT(session_timeout
);
3356 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3358 int next_state
= session
[s
].ppp
.ipv6cp
;
3359 switch (session
[s
].ppp
.ipv6cp
)
3363 next_state
= RequestSent
;
3366 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3368 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3369 sendipv6cp(s
, session
[s
].tunnel
);
3370 change_state(s
, ipv6cp
, next_state
);
3374 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3375 change_state(s
, ipv6cp
, Stopped
);
3382 if (sess_local
[s
].ccp
.restart
<= time_now
)
3384 int next_state
= session
[s
].ppp
.ccp
;
3385 switch (session
[s
].ppp
.ccp
)
3389 next_state
= RequestSent
;
3392 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3394 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3395 sendccp(s
, session
[s
].tunnel
);
3396 change_state(s
, ccp
, next_state
);
3400 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3401 change_state(s
, ccp
, Stopped
);
3408 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3409 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3411 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3412 STAT(session_timeout
);
3417 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3418 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3419 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3421 uint8_t b
[MAXETHER
];
3423 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3427 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3428 *(uint16_t *)(q
+ 2) = htons(8); // Length
3429 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3431 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3432 (int)(time_now
- session
[s
].last_packet
));
3433 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3434 sess_local
[s
].last_echo
= time_now
;
3438 // Drop sessions who have reached session_timeout seconds
3439 if (session
[s
].session_timeout
)
3441 bundleidt bid
= session
[s
].bundle
;
3444 if (time_now
- bundle
[bid
].last_check
>= 1)
3446 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3447 bundle
[bid
].last_check
= time_now
;
3448 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3451 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3453 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3460 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3462 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3468 // Drop sessions who have reached idle_timeout seconds
3469 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3471 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3472 STAT(session_timeout
);
3477 // Check for actions requested from the CLI
3478 if ((a
= cli_session_actions
[s
].action
))
3482 cli_session_actions
[s
].action
= 0;
3483 if (a
& CLI_SESS_KILL
)
3485 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3486 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3487 a
= 0; // dead, no need to check for other actions
3491 if (a
& CLI_SESS_NOSNOOP
)
3493 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3494 session
[s
].snoop_ip
= 0;
3495 session
[s
].snoop_port
= 0;
3499 else if (a
& CLI_SESS_SNOOP
)
3501 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3502 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3503 cli_session_actions
[s
].snoop_port
);
3505 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3506 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3511 if (a
& CLI_SESS_NOTHROTTLE
)
3513 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3514 throttle_session(s
, 0, 0);
3518 else if (a
& CLI_SESS_THROTTLE
)
3520 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3521 cli_session_actions
[s
].throttle_in
,
3522 cli_session_actions
[s
].throttle_out
);
3524 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3529 if (a
& CLI_SESS_NOFILTER
)
3531 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3532 filter_session(s
, 0, 0);
3536 else if (a
& CLI_SESS_FILTER
)
3538 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3539 cli_session_actions
[s
].filter_in
,
3540 cli_session_actions
[s
].filter_out
);
3542 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3548 cluster_send_session(s
);
3551 // RADIUS interim accounting
3552 if (config
->radius_accounting
&& config
->radius_interim
> 0
3553 && session
[s
].ip
&& !session
[s
].walled_garden
3554 && !sess_local
[s
].radius
// RADIUS already in progress
3555 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3556 && session
[s
].flags
& SESSION_STARTED
)
3558 int rad
= radiusnew(s
);
3561 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3562 STAT(radius_overflow
);
3566 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3567 session
[s
].user
, session
[s
].unique_id
);
3569 radiussend(rad
, RADIUSINTERIM
);
3570 sess_local
[s
].last_interim
= time_now
;
3575 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3576 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3580 // Are we in the middle of a tunnel update, or radius
3583 static int still_busy(void)
3586 static clockt last_talked
= 0;
3587 static clockt start_busy_wait
= 0;
3590 static time_t stopped_bgp
= 0;
3595 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3597 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3598 if (bgp_peers
[i
].state
== Established
)
3599 bgp_stop(&bgp_peers
[i
]);
3601 stopped_bgp
= time_now
;
3603 if (!config
->cluster_iam_master
)
3605 // we don't want to become master
3606 cluster_send_ping(0);
3612 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3617 if (!config
->cluster_iam_master
)
3620 if (main_quit
== QUIT_SHUTDOWN
)
3622 static int dropped
= 0;
3627 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3628 for (i
= 1; i
< MAXTUNNEL
; i
++)
3629 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3630 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3636 if (start_busy_wait
== 0)
3637 start_busy_wait
= TIME
;
3639 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3641 if (!tunnel
[i
].controlc
)
3644 if (last_talked
!= TIME
)
3646 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3652 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3653 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3655 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3659 for (i
= 1; i
< MAXRADIUS
; i
++)
3661 if (radius
[i
].state
== RADIUSNULL
)
3663 if (radius
[i
].state
== RADIUSWAIT
)
3666 if (last_talked
!= TIME
)
3668 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3678 # include <sys/epoll.h>
3680 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3681 # include "fake_epoll.h"
3684 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3687 // additional polled fds
3689 # define EXTRA_FDS BGP_NUM_PEERS
3691 # define EXTRA_FDS 0
3694 // main loop - gets packets on tun or udp and processes them
3695 static void mainloop(void)
3699 clockt next_cluster_ping
= 0; // send initial ping immediately
3700 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3701 int maxevent
= sizeof(events
)/sizeof(*events
);
3703 if ((epollfd
= epoll_create(maxevent
)) < 0)
3705 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3709 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3710 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3712 /* setup our fds to poll for input */
3714 static struct event_data d
[BASE_FDS
];
3715 struct epoll_event e
;
3722 d
[i
].type
= FD_TYPE_CLI
;
3723 e
.data
.ptr
= &d
[i
++];
3724 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3727 d
[i
].type
= FD_TYPE_CLUSTER
;
3728 e
.data
.ptr
= &d
[i
++];
3729 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3731 d
[i
].type
= FD_TYPE_TUN
;
3732 e
.data
.ptr
= &d
[i
++];
3733 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3735 d
[i
].type
= FD_TYPE_UDP
;
3736 e
.data
.ptr
= &d
[i
++];
3737 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3739 d
[i
].type
= FD_TYPE_CONTROL
;
3740 e
.data
.ptr
= &d
[i
++];
3741 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3743 d
[i
].type
= FD_TYPE_DAE
;
3744 e
.data
.ptr
= &d
[i
++];
3745 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3747 d
[i
].type
= FD_TYPE_NETLINK
;
3748 e
.data
.ptr
= &d
[i
++];
3749 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3753 signal(SIGPIPE
, SIG_IGN
);
3754 bgp_setup(config
->as_number
);
3755 if (config
->bind_address
)
3756 bgp_add_route(config
->bind_address
, 0xffffffff);
3758 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3760 if (config
->neighbour
[i
].name
[0])
3761 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3762 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3763 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
3764 0); /* 0 = routing disabled */
3768 while (!main_quit
|| still_busy())
3778 config
->reload_config
++;
3781 if (config
->reload_config
)
3783 config
->reload_config
= 0;
3791 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3792 STAT(select_called
);
3797 if (errno
== EINTR
||
3798 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3801 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3807 struct sockaddr_in addr
;
3808 struct in_addr local
;
3813 int cluster_ready
= 0;
3816 int cluster_pkts
= 0;
3818 uint32_t bgp_events
[BGP_NUM_PEERS
];
3819 memset(bgp_events
, 0, sizeof(bgp_events
));
3822 for (c
= n
, i
= 0; i
< c
; i
++)
3824 struct event_data
*d
= events
[i
].data
.ptr
;
3828 case FD_TYPE_CLI
: // CLI connections
3832 alen
= sizeof(addr
);
3833 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3839 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3845 // these are handled below, with multiple interleaved reads
3846 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3847 case FD_TYPE_TUN
: tun_ready
++; break;
3848 case FD_TYPE_UDP
: udp_ready
++; break;
3850 case FD_TYPE_CONTROL
: // nsctl commands
3851 alen
= sizeof(addr
);
3852 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3853 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3857 case FD_TYPE_DAE
: // DAE requests
3858 alen
= sizeof(addr
);
3859 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3860 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3864 case FD_TYPE_RADIUS
: // RADIUS response
3865 alen
= sizeof(addr
);
3866 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3867 if (s
>= 0 && config
->cluster_iam_master
)
3869 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3870 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3871 processrad(buf
, s
, d
->index
);
3873 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3874 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3882 bgp_events
[d
->index
] = events
[i
].events
;
3887 case FD_TYPE_NETLINK
:
3889 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
3890 s
= netlink_recv(buf
, sizeof(buf
));
3891 if (nh
->nlmsg_type
== NLMSG_ERROR
)
3893 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
3896 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
3898 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
3903 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
3908 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
);
3914 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3919 bgp_process(bgp_events
);
3922 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3927 alen
= sizeof(addr
);
3928 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3930 processudp(buf
, s
, &addr
);
3943 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3958 alen
= sizeof(addr
);
3959 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3961 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3972 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3973 STAT(multi_read_used
);
3975 if (c
>= config
->multi_read_count
)
3977 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3978 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3980 STAT(multi_read_exceeded
);
3986 /* no event received, but timers could still have expired */
3987 bgp_process_peers_timers();
3992 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
3994 // Log current traffic stats
3995 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3996 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3997 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
3998 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
3999 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4001 udp_tx
= udp_rx
= 0;
4002 udp_rx_pkt
= eth_rx_pkt
= 0;
4003 eth_tx
= eth_rx
= 0;
4006 if (config
->dump_speed
)
4007 printf("%s\n", config
->bandwidth
);
4009 // Update the internal time counter
4010 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4014 struct param_timer p
= { time_now
};
4015 run_plugins(PLUGIN_TIMER
, &p
);
4019 // Runs on every machine (master and slaves).
4020 if (next_cluster_ping
<= TIME
)
4022 // Check to see which of the cluster is still alive..
4024 cluster_send_ping(basetime
); // Only does anything if we're a slave
4025 cluster_check_master(); // ditto.
4027 cluster_heartbeat(); // Only does anything if we're a master.
4028 cluster_check_slaves(); // ditto.
4030 master_update_counts(); // If we're a slave, send our byte counters to our master.
4032 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4033 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4035 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4038 if (!config
->cluster_iam_master
)
4041 // Run token bucket filtering queue..
4042 // Only run it every 1/10th of a second.
4044 static clockt last_run
= 0;
4045 if (last_run
!= TIME
)
4052 // Handle timeouts, retries etc.
4054 static double last_clean
= 0;
4058 TIME
= now(&this_clean
);
4059 diff
= this_clean
- last_clean
;
4061 // Run during idle time (after we've handled
4062 // all incoming packets) or every 1/10th sec
4063 if (!more
|| diff
> 0.1)
4065 regular_cleanups(diff
);
4066 last_clean
= this_clean
;
4070 if (*config
->accounting_dir
)
4072 static clockt next_acct
= 0;
4073 static clockt next_shut_acct
= 0;
4075 if (next_acct
<= TIME
)
4077 // Dump accounting data
4078 next_acct
= TIME
+ ACCT_TIME
;
4079 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4082 else if (next_shut_acct
<= TIME
)
4084 // Dump accounting data for shutdown sessions
4085 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4092 // Are we the master and shutting down??
4093 if (config
->cluster_iam_master
)
4094 cluster_heartbeat(); // Flush any queued changes..
4096 // Ok. Notify everyone we're shutting down. If we're
4097 // the master, this will force an election.
4098 cluster_send_ping(0);
4101 // Important!!! We MUST not process any packets past this point!
4102 LOG(1, 0, 0, "Shutdown complete\n");
4105 static void stripdomain(char *host
)
4109 if ((p
= strchr(host
, '.')))
4115 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4121 while (fgets(buf
, sizeof(buf
), resolv
))
4123 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4126 if (!isspace(buf
[6]))
4130 while (isspace(*b
)) b
++;
4135 while (*b
&& !isspace(*b
)) b
++;
4137 if (buf
[0] == 'd') // domain is canonical
4143 // first search line
4146 // hold, may be subsequent domain line
4147 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4158 int hl
= strlen(host
);
4159 int dl
= strlen(domain
);
4160 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4161 host
[hl
-dl
- 1] = 0;
4165 *p
= 0; // everything after first dot
4170 // Init data structures
4171 static void initdata(int optdebug
, char *optconfig
)
4175 if (!(config
= shared_malloc(sizeof(configt
))))
4177 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4181 memset(config
, 0, sizeof(configt
));
4182 time(&config
->start_time
);
4183 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4184 config
->debug
= optdebug
;
4185 config
->num_tbfs
= MAXTBFS
;
4186 config
->rl_rate
= 28; // 28kbps
4187 config
->cluster_mcast_ttl
= 1;
4188 config
->cluster_master_min_adv
= 1;
4189 config
->ppp_restart_time
= 3;
4190 config
->ppp_max_configure
= 10;
4191 config
->ppp_max_failure
= 5;
4192 config
->kill_timedout_sessions
= 1;
4193 strcpy(config
->random_device
, RANDOMDEVICE
);
4195 log_stream
= stderr
;
4198 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4200 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4203 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4206 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4208 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4211 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4213 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4216 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4218 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4221 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4223 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4226 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4228 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4232 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4234 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4238 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4240 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4244 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4246 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4250 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4252 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4255 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4257 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4259 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4262 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4264 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4266 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4269 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4271 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4272 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4273 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4274 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4275 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4277 // Put all the sessions on the free list marked as undefined.
4278 for (i
= 1; i
< MAXSESSION
; i
++)
4280 session
[i
].next
= i
+ 1;
4281 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4283 session
[MAXSESSION
- 1].next
= 0;
4286 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4287 for (i
= 1; i
< MAXTUNNEL
; i
++)
4288 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4290 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4291 bundle
[i
].state
= BUNDLEUNDEF
;
4296 // Grab my hostname unless it's been specified
4297 gethostname(hostname
, sizeof(hostname
));
4298 stripdomain(hostname
);
4301 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4304 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4306 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4312 static int assign_ip_address(sessionidt s
)
4316 time_t best_time
= time_now
;
4317 char *u
= session
[s
].user
;
4321 CSTAT(assign_ip_address
);
4323 for (i
= 1; i
< ip_pool_size
; i
++)
4325 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4328 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4335 if (ip_address_pool
[i
].last
< best_time
)
4338 if (!(best_time
= ip_address_pool
[i
].last
))
4339 break; // never used, grab this one
4345 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4349 session
[s
].ip
= ip_address_pool
[best
].address
;
4350 session
[s
].ip_pool_index
= best
;
4351 ip_address_pool
[best
].assigned
= 1;
4352 ip_address_pool
[best
].last
= time_now
;
4353 ip_address_pool
[best
].session
= s
;
4354 if (session
[s
].walled_garden
)
4355 /* Don't track addresses of users in walled garden (note: this
4356 means that their address isn't "sticky" even if they get
4358 ip_address_pool
[best
].user
[0] = 0;
4360 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4363 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4364 reuse
? "Reusing" : "Allocating", best
);
4369 static void free_ip_address(sessionidt s
)
4371 int i
= session
[s
].ip_pool_index
;
4374 CSTAT(free_ip_address
);
4377 return; // what the?
4379 if (i
< 0) // Is this actually part of the ip pool?
4383 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4385 ip_address_pool
[i
].assigned
= 0;
4386 ip_address_pool
[i
].session
= 0;
4387 ip_address_pool
[i
].last
= time_now
;
4391 // Fsck the address pool against the session table.
4392 // Normally only called when we become a master.
4394 // This isn't perfect: We aren't keep tracking of which
4395 // users used to have an IP address.
4397 void rebuild_address_pool(void)
4402 // Zero the IP pool allocation, and build
4403 // a map from IP address to pool index.
4404 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4406 ip_address_pool
[i
].assigned
= 0;
4407 ip_address_pool
[i
].session
= 0;
4408 if (!ip_address_pool
[i
].address
)
4411 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4414 for (i
= 0; i
< MAXSESSION
; ++i
)
4417 if (!(session
[i
].opened
&& session
[i
].ip
))
4420 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4422 if (session
[i
].ip_pool_index
< 0)
4424 // Not allocated out of the pool.
4425 if (ipid
< 1) // Not found in the pool either? good.
4428 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4429 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4431 // Fall through and process it as part of the pool.
4435 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4437 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4439 session
[i
].ip_pool_index
= ipid
;
4443 ip_address_pool
[ipid
].assigned
= 1;
4444 ip_address_pool
[ipid
].session
= i
;
4445 ip_address_pool
[ipid
].last
= time_now
;
4446 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4447 session
[i
].ip_pool_index
= ipid
;
4448 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4453 // Fix the address pool to match a changed session.
4454 // (usually when the master sends us an update).
4455 static void fix_address_pool(int sid
)
4459 ipid
= session
[sid
].ip_pool_index
;
4461 if (ipid
> ip_pool_size
)
4462 return; // Ignore it. rebuild_address_pool will fix it up.
4464 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4465 return; // Just ignore it. rebuild_address_pool will take care of it.
4467 ip_address_pool
[ipid
].assigned
= 1;
4468 ip_address_pool
[ipid
].session
= sid
;
4469 ip_address_pool
[ipid
].last
= time_now
;
4470 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4474 // Add a block of addresses to the IP pool to hand out.
4476 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4480 prefixlen
= 32; // Host route only.
4482 addr
&= 0xffffffff << (32 - prefixlen
);
4484 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4487 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4489 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4490 continue; // Skip 0 and broadcast addresses.
4492 ip_address_pool
[ip_pool_size
].address
= i
;
4493 ip_address_pool
[ip_pool_size
].assigned
= 0;
4495 if (ip_pool_size
>= MAXIPPOOL
)
4497 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4503 // Initialize the IP address pool
4504 static void initippool()
4509 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4511 if (!(f
= fopen(IPPOOLFILE
, "r")))
4513 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4517 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4520 buf
[4095] = 0; // Force it to be zero terminated/
4522 if (*buf
== '#' || *buf
== '\n')
4523 continue; // Skip comments / blank lines
4524 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4525 if ((p
= (char *)strchr(buf
, ':')))
4529 src
= inet_addr(buf
);
4530 if (src
== INADDR_NONE
)
4532 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4535 // This entry is for a specific IP only
4536 if (src
!= config
->bind_address
)
4541 if ((p
= (char *)strchr(pool
, '/')))
4545 in_addr_t start
= 0;
4547 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4549 if (!*p
|| !(numbits
= atoi(p
)))
4551 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4554 start
= ntohl(inet_addr(pool
));
4556 // Add a static route for this pool
4557 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4558 fmtaddr(htonl(start
), 0), numbits
);
4560 routeset(0, start
, numbits
, 0, 1);
4562 add_to_ip_pool(start
, numbits
);
4566 // It's a single ip address
4567 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4571 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4574 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4576 struct sockaddr_in snoop_addr
= {0};
4577 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4580 snoop_addr
.sin_family
= AF_INET
;
4581 snoop_addr
.sin_addr
.s_addr
= destination
;
4582 snoop_addr
.sin_port
= ntohs(port
);
4584 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4585 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4586 htons(snoop_addr
.sin_port
));
4588 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4589 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4591 STAT(packets_snooped
);
4594 static int dump_session(FILE **f
, sessiont
*s
)
4596 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4601 char filename
[1024];
4603 time_t now
= time(NULL
);
4605 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4606 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4608 if (!(*f
= fopen(filename
, "w")))
4610 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4614 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4615 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4620 "# format: username ip qos uptxoctets downrxoctets\n",
4622 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4627 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4628 fprintf(*f
, "%s %s %d %u %u\n",
4629 s
->user
, // username
4630 fmtaddr(htonl(s
->ip
), 0), // ip
4631 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4632 (uint32_t) s
->cin_delta
, // uptxoctets
4633 (uint32_t) s
->cout_delta
); // downrxoctets
4635 s
->cin_delta
= s
->cout_delta
= 0;
4640 static void dump_acct_info(int all
)
4646 CSTAT(dump_acct_info
);
4650 for (i
= 0; i
< shut_acct_n
; i
++)
4651 dump_session(&f
, &shut_acct
[i
]);
4657 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4658 dump_session(&f
, &session
[i
]);
4665 int main(int argc
, char *argv
[])
4669 char *optconfig
= CONFIGFILE
;
4671 time(&basetime
); // start clock
4674 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4679 if (fork()) exit(0);
4681 freopen("/dev/null", "r", stdin
);
4682 freopen("/dev/null", "w", stdout
);
4683 freopen("/dev/null", "w", stderr
);
4692 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4695 printf("Args are:\n"
4696 "\t-d\t\tDetach from terminal\n"
4697 "\t-c <file>\tConfig file\n"
4698 "\t-h <hostname>\tForce hostname\n"
4706 // Start the timer routine off
4708 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4711 initdata(optdebug
, optconfig
);
4715 /* set hostname /after/ having read the config file */
4716 if (*config
->hostname
)
4717 strcpy(hostname
, config
->hostname
);
4718 cli_init_complete(hostname
);
4720 init_tbf(config
->num_tbfs
);
4722 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4723 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4724 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4727 rlim
.rlim_cur
= RLIM_INFINITY
;
4728 rlim
.rlim_max
= RLIM_INFINITY
;
4729 // Remove the maximum core size
4730 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4731 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4733 // Make core dumps go to /tmp
4737 if (config
->scheduler_fifo
)
4740 struct sched_param params
= {0};
4741 params
.sched_priority
= 1;
4743 if (get_nprocs() < 2)
4745 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4746 config
->scheduler_fifo
= 0;
4750 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4752 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4756 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4757 config
->scheduler_fifo
= 0;
4764 /* Set up the cluster communications port. */
4765 if (cluster_init() < 0)
4769 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4777 unsigned seed
= time_now
^ getpid();
4778 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4782 signal(SIGHUP
, sighup_handler
);
4783 signal(SIGCHLD
, sigchild_handler
);
4784 signal(SIGTERM
, shutdown_handler
);
4785 signal(SIGINT
, shutdown_handler
);
4786 signal(SIGQUIT
, shutdown_handler
);
4788 // Prevent us from getting paged out
4789 if (config
->lock_pages
)
4791 if (!mlockall(MCL_CURRENT
))
4792 LOG(1, 0, 0, "Locking pages into memory\n");
4794 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4799 /* remove plugins (so cleanup code gets run) */
4802 // Remove the PID file if we wrote it
4803 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4804 unlink(config
->pid_file
);
4806 /* kill CLI children */
4807 signal(SIGTERM
, SIG_IGN
);
4812 static void sighup_handler(int sig
)
4817 static void shutdown_handler(int sig
)
4819 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4822 static void sigchild_handler(int sig
)
4824 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4828 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4831 *challenge_response
= NULL
;
4833 if (!*config
->l2tp_secret
)
4835 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4839 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4841 *challenge_response
= calloc(17, 1);
4844 MD5_Update(&ctx
, &id
, 1);
4845 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4846 MD5_Update(&ctx
, challenge
, challenge_length
);
4847 MD5_Final(*challenge_response
, &ctx
);
4852 static int facility_value(char *name
)
4855 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4857 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4858 return facilitynames
[i
].c_val
;
4863 static void update_config()
4867 static int timeout
= 0;
4868 static int interval
= 0;
4875 if (log_stream
!= stderr
)
4881 if (*config
->log_filename
)
4883 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4885 char *p
= config
->log_filename
+ 7;
4888 openlog("l2tpns", LOG_PID
, facility_value(p
));
4892 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4894 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4896 fseek(log_stream
, 0, SEEK_END
);
4897 setbuf(log_stream
, NULL
);
4901 log_stream
= stderr
;
4902 setbuf(log_stream
, NULL
);
4908 log_stream
= stderr
;
4909 setbuf(log_stream
, NULL
);
4912 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4913 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4915 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4916 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4917 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4919 // reset MRU/MSS globals
4920 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4921 if (MRU
> PPPoE_MRU
)
4924 MSS
= MRU
- TCP_HDRS
;
4927 config
->numradiusservers
= 0;
4928 for (i
= 0; i
< MAXRADSERVER
; i
++)
4929 if (config
->radiusserver
[i
])
4931 config
->numradiusservers
++;
4932 // Set radius port: if not set, take the port from the
4933 // first radius server. For the first radius server,
4934 // take the #defined default value from l2tpns.h
4936 // test twice, In case someone works with
4937 // a secondary radius server without defining
4938 // a primary one, this will work even then.
4939 if (i
> 0 && !config
->radiusport
[i
])
4940 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4941 if (!config
->radiusport
[i
])
4942 config
->radiusport
[i
] = RADPORT
;
4945 if (!config
->numradiusservers
)
4946 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4948 // parse radius_authtypes_s
4949 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4950 p
= config
->radius_authtypes_s
;
4953 char *s
= strpbrk(p
, " \t,");
4959 while (*s
== ' ' || *s
== '\t')
4966 if (!strncasecmp("chap", p
, strlen(p
)))
4968 else if (!strncasecmp("pap", p
, strlen(p
)))
4971 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4973 config
->radius_authtypes
|= type
;
4974 if (!config
->radius_authprefer
)
4975 config
->radius_authprefer
= type
;
4980 if (!config
->radius_authtypes
)
4982 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4983 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4986 // normalise radius_authtypes_s
4987 if (config
->radius_authprefer
== AUTHPAP
)
4989 strcpy(config
->radius_authtypes_s
, "pap");
4990 if (config
->radius_authtypes
& AUTHCHAP
)
4991 strcat(config
->radius_authtypes_s
, ", chap");
4995 strcpy(config
->radius_authtypes_s
, "chap");
4996 if (config
->radius_authtypes
& AUTHPAP
)
4997 strcat(config
->radius_authtypes_s
, ", pap");
5000 if (!config
->radius_dae_port
)
5001 config
->radius_dae_port
= DAEPORT
;
5003 // re-initialise the random number source
5004 initrandom(config
->random_device
);
5007 for (i
= 0; i
< MAXPLUGINS
; i
++)
5009 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5012 if (*config
->plugins
[i
])
5015 add_plugin(config
->plugins
[i
]);
5017 else if (*config
->old_plugins
[i
])
5020 remove_plugin(config
->old_plugins
[i
]);
5025 guest_accounts_num
= 0;
5026 char *p2
= config
->guest_user
;
5029 char *s
= strpbrk(p2
, " \t,");
5033 while (*s
== ' ' || *s
== '\t')
5040 strcpy(guest_users
[guest_accounts_num
], p2
);
5041 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5042 guest_accounts_num
++;
5045 // Rebuild the guest_user array
5046 strcpy(config
->guest_user
, "");
5048 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5050 strcat(config
->guest_user
, guest_users
[ui
]);
5051 if (ui
<guest_accounts_num
-1)
5053 strcat(config
->guest_user
, ",");
5058 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5059 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5060 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5061 if (!*config
->cluster_interface
)
5062 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5064 if (!config
->cluster_hb_interval
)
5065 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5067 if (!config
->cluster_hb_timeout
)
5068 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5070 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5072 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5073 // late, ensure we're sufficiently larger than that
5074 int t
= 4 * config
->cluster_hb_interval
+ 11;
5076 if (config
->cluster_hb_timeout
< t
)
5078 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5079 config
->cluster_hb_timeout
= t
;
5082 // Push timing changes to the slaves immediately if we're the master
5083 if (config
->cluster_iam_master
)
5084 cluster_heartbeat();
5086 interval
= config
->cluster_hb_interval
;
5087 timeout
= config
->cluster_hb_timeout
;
5091 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5094 if ((f
= fopen(config
->pid_file
, "w")))
5096 fprintf(f
, "%d\n", getpid());
5098 config
->wrote_pid
= 1;
5102 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5107 static void read_config_file()
5111 if (!config
->config_file
) return;
5112 if (!(f
= fopen(config
->config_file
, "r")))
5114 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5118 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5120 LOG(3, 0, 0, "Done reading config file\n");
5124 int sessionsetup(sessionidt s
, tunnelidt t
)
5126 // A session now exists, set it up
5132 CSTAT(sessionsetup
);
5134 LOG(3, s
, t
, "Doing session setup for session\n");
5136 // Join a bundle if the MRRU option is accepted
5137 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5139 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5140 if (join_bundle(s
) > 0)
5141 cluster_send_bundle(session
[s
].bundle
);
5144 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5145 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5152 assign_ip_address(s
);
5155 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5156 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5159 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5160 fmtaddr(htonl(session
[s
].ip
), 0));
5164 // Make sure this is right
5165 session
[s
].tunnel
= t
;
5167 // zap old sessions with same IP and/or username
5168 // Don't kill gardened sessions - doing so leads to a DoS
5169 // from someone who doesn't need to know the password
5172 user
= session
[s
].user
;
5173 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5175 if (i
== s
) continue;
5176 if (!session
[s
].opened
) continue;
5177 // Allow duplicate sessions for multilink ones of the same bundle.
5178 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5180 if (ip
== session
[i
].ip
)
5182 sessionkill(i
, "Duplicate IP address");
5186 if (config
->allow_duplicate_users
) continue;
5187 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5191 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5193 if (!strcasecmp(user
, guest_users
[gu
]))
5199 if (found
) continue;
5201 // Drop the new session in case of duplicate sessionss, not the old one.
5202 if (!strcasecmp(user
, session
[i
].user
))
5203 sessionkill(i
, "Duplicate session for users");
5207 // no need to set a route for the same IP address of the bundle
5208 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5212 // Add the route for this session.
5213 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5215 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5216 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5219 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5222 // Static IPs need to be routed if not already
5223 // convered by a Framed-Route. Anything else is part
5224 // of the IP address pool and is already routed, it
5225 // just needs to be added to the IP cache.
5226 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5227 if (session
[s
].ip_pool_index
== -1) // static ip
5229 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5232 cache_ipmap(session
[s
].ip
, s
);
5235 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5236 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5238 // Run the plugin's against this new session.
5240 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5241 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5244 // Allocate TBFs if throttled
5245 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5246 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5248 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5250 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5251 fmtaddr(htonl(session
[s
].ip
), 0),
5252 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5254 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5256 return 1; // RADIUS OK and IP allocated, done...
5260 // This session just got dropped on us by the master or something.
5261 // Make sure our tables up up to date...
5263 int load_session(sessionidt s
, sessiont
*new)
5269 if (new->ip_pool_index
>= MAXIPPOOL
||
5270 new->tunnel
>= MAXTUNNEL
)
5272 LOG(0, s
, 0, "Strange session update received!\n");
5273 // FIXME! What to do here?
5278 // Ok. All sanity checks passed. Now we're committed to
5279 // loading the new session.
5282 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5284 // See if routes/ip cache need updating
5285 if (new->ip
!= session
[s
].ip
)
5288 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5289 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5290 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5298 // remove old routes...
5299 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5301 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5302 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5305 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5311 if (session
[s
].ip_pool_index
== -1) // static IP
5313 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5315 else // It's part of the IP pool, remove it manually.
5316 uncache_ipmap(session
[s
].ip
);
5321 // add new routes...
5322 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5324 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5325 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5328 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5334 // If there's a new one, add it.
5335 if (new->ip_pool_index
== -1)
5337 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5340 cache_ipmap(new->ip
, s
);
5345 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5346 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5349 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5351 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5355 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5357 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5358 new->filter_out
= 0;
5361 if (new->filter_in
!= session
[s
].filter_in
)
5363 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5364 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5367 if (new->filter_out
!= session
[s
].filter_out
)
5369 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5370 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5373 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5374 // for walking the sessions to forward byte counts to the master.
5375 config
->cluster_highest_sessionid
= s
;
5377 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5379 // Do fixups into address pool.
5380 if (new->ip_pool_index
!= -1)
5381 fix_address_pool(s
);
5386 static void initplugins()
5390 loaded_plugins
= ll_init();
5391 // Initialize the plugins to nothing
5392 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5393 plugins
[i
] = ll_init();
5396 static void *open_plugin(char *plugin_name
, int load
)
5398 char path
[256] = "";
5400 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5401 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5402 return dlopen(path
, RTLD_NOW
);
5405 // plugin callback to get a config value
5406 static void *getconfig(char *key
, enum config_typet type
)
5410 for (i
= 0; config_values
[i
].key
; i
++)
5412 if (!strcmp(config_values
[i
].key
, key
))
5414 if (config_values
[i
].type
== type
)
5415 return ((void *) config
) + config_values
[i
].offset
;
5417 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5418 key
, type
, config_values
[i
].type
);
5424 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5428 static int add_plugin(char *plugin_name
)
5430 static struct pluginfuncs funcs
= {
5435 sessiontbysessionidt
,
5436 sessionidtbysessiont
,
5443 cluster_send_session
,
5446 void *p
= open_plugin(plugin_name
, 1);
5447 int (*initfunc
)(struct pluginfuncs
*);
5452 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5456 if (ll_contains(loaded_plugins
, p
))
5459 return 0; // already loaded
5463 int *v
= dlsym(p
, "plugin_api_version");
5464 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5466 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5472 if ((initfunc
= dlsym(p
, "plugin_init")))
5474 if (!initfunc(&funcs
))
5476 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5482 ll_push(loaded_plugins
, p
);
5484 for (i
= 0; i
< max_plugin_functions
; i
++)
5487 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5489 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5490 ll_push(plugins
[i
], x
);
5494 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5498 static void run_plugin_done(void *plugin
)
5500 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5506 static int remove_plugin(char *plugin_name
)
5508 void *p
= open_plugin(plugin_name
, 0);
5514 if (ll_contains(loaded_plugins
, p
))
5517 for (i
= 0; i
< max_plugin_functions
; i
++)
5520 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5521 ll_delete(plugins
[i
], x
);
5524 ll_delete(loaded_plugins
, p
);
5530 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5534 int run_plugins(int plugin_type
, void *data
)
5536 int (*func
)(void *data
);
5538 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5539 return PLUGIN_RET_ERROR
;
5541 ll_reset(plugins
[plugin_type
]);
5542 while ((func
= ll_next(plugins
[plugin_type
])))
5546 if (r
!= PLUGIN_RET_OK
)
5547 return r
; // stop here
5550 return PLUGIN_RET_OK
;
5553 static void plugins_done()
5557 ll_reset(loaded_plugins
);
5558 while ((p
= ll_next(loaded_plugins
)))
5562 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5564 struct nsctl request
;
5565 struct nsctl response
;
5566 int type
= unpack_control(&request
, buf
, len
);
5570 if (log_stream
&& config
->debug
>= 4)
5574 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5575 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5579 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5580 dump_control(&request
, log_stream
);
5586 case NSCTL_REQ_LOAD
:
5587 if (request
.argc
!= 1)
5589 response
.type
= NSCTL_RES_ERR
;
5591 response
.argv
[0] = "name of plugin required";
5593 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5595 response
.type
= NSCTL_RES_ERR
;
5597 response
.argv
[0] = !r
5598 ? "plugin already loaded"
5599 : "error loading plugin";
5603 response
.type
= NSCTL_RES_OK
;
5609 case NSCTL_REQ_UNLOAD
:
5610 if (request
.argc
!= 1)
5612 response
.type
= NSCTL_RES_ERR
;
5614 response
.argv
[0] = "name of plugin required";
5616 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5618 response
.type
= NSCTL_RES_ERR
;
5620 response
.argv
[0] = !r
5621 ? "plugin not loaded"
5622 : "plugin not found";
5626 response
.type
= NSCTL_RES_OK
;
5632 case NSCTL_REQ_HELP
:
5633 response
.type
= NSCTL_RES_OK
;
5636 ll_reset(loaded_plugins
);
5637 while ((p
= ll_next(loaded_plugins
)))
5639 char **help
= dlsym(p
, "plugin_control_help");
5640 while (response
.argc
< 0xff && help
&& *help
)
5641 response
.argv
[response
.argc
++] = *help
++;
5646 case NSCTL_REQ_CONTROL
:
5648 struct param_control param
= {
5649 config
->cluster_iam_master
,
5656 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5658 if (r
== PLUGIN_RET_ERROR
)
5660 response
.type
= NSCTL_RES_ERR
;
5662 response
.argv
[0] = param
.additional
5664 : "error returned by plugin";
5666 else if (r
== PLUGIN_RET_NOTMASTER
)
5668 static char msg
[] = "must be run on master: 000.000.000.000";
5670 response
.type
= NSCTL_RES_ERR
;
5672 if (config
->cluster_master_address
)
5674 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5675 response
.argv
[0] = msg
;
5679 response
.argv
[0] = "must be run on master: none elected";
5682 else if (!(param
.response
& NSCTL_RESPONSE
))
5684 response
.type
= NSCTL_RES_ERR
;
5686 response
.argv
[0] = param
.response
5687 ? "unrecognised response value from plugin"
5688 : "unhandled action";
5692 response
.type
= param
.response
;
5694 if (param
.additional
)
5697 response
.argv
[0] = param
.additional
;
5705 response
.type
= NSCTL_RES_ERR
;
5707 response
.argv
[0] = "error unpacking control packet";
5710 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5713 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5717 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5720 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5721 if (log_stream
&& config
->debug
>= 4)
5723 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5724 dump_control(&response
, log_stream
);
5728 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5729 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5734 static tunnelidt
new_tunnel()
5737 for (i
= 1; i
< MAXTUNNEL
; i
++)
5739 if (tunnel
[i
].state
== TUNNELFREE
)
5741 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5742 if (i
> config
->cluster_highest_tunnelid
)
5743 config
->cluster_highest_tunnelid
= i
;
5747 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5752 // We're becoming the master. Do any required setup..
5754 // This is principally telling all the plugins that we're
5755 // now a master, and telling them about all the sessions
5756 // that are active too..
5758 void become_master(void)
5761 static struct event_data d
[RADIUS_FDS
];
5762 struct epoll_event e
;
5764 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5766 // running a bunch of iptables commands is slow and can cause
5767 // the master to drop tunnels on takeover--kludge around the
5768 // problem by forking for the moment (note: race)
5769 if (!fork_and_close())
5771 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5773 if (!session
[s
].opened
) // Not an in-use session.
5776 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5783 for (i
= 0; i
< RADIUS_FDS
; i
++)
5785 d
[i
].type
= FD_TYPE_RADIUS
;
5789 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5793 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5799 if (CLI_HELP_REQUESTED
)
5800 return CLI_HELP_NO_ARGS
;
5803 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5805 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5808 if (!session
[s
].opened
)
5811 idle
= time_now
- session
[s
].last_data
;
5812 idle
/= 5 ; // In multiples of 5 seconds.
5822 for (i
= 0; i
< 63; ++i
)
5824 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5826 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5827 cli_print(cli
, "%d total sessions open.", count
);
5831 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5837 if (CLI_HELP_REQUESTED
)
5838 return CLI_HELP_NO_ARGS
;
5841 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5843 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5846 if (!session
[s
].opened
)
5849 d
= time_now
- session
[s
].opened
;
5852 while (d
> 1 && open
< 32)
5862 for (i
= 0; i
< 30; ++i
)
5864 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5867 cli_print(cli
, "%d total sessions open.", count
);
5873 * This unencodes the AVP using the L2TP secret and the previously
5874 * stored random vector. It overwrites the hidden data with the
5875 * unhidden AVP subformat.
5877 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5883 uint16_t m
= htons(type
);
5885 // Compute initial pad
5887 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5888 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5889 MD5_Update(&ctx
, vector
, vec_len
);
5890 MD5_Final(digest
, &ctx
);
5892 // pointer to last decoded 16 octets
5897 // calculate a new pad based on the last decoded block
5898 if (d
>= sizeof(digest
))
5901 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5902 MD5_Update(&ctx
, last
, sizeof(digest
));
5903 MD5_Final(digest
, &ctx
);
5909 *value
++ ^= digest
[d
++];
5914 int find_filter(char const *name
, size_t len
)
5919 for (i
= 0; i
< MAXFILTER
; i
++)
5921 if (!*ip_filters
[i
].name
)
5929 if (strlen(ip_filters
[i
].name
) != len
)
5932 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5939 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5943 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5944 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5945 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5946 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5947 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5953 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5957 case FILTER_FLAG_OP_ANY
:
5958 return (flags
& sflags
) || (~flags
& cflags
);
5960 case FILTER_FLAG_OP_ALL
:
5961 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5963 case FILTER_FLAG_OP_EST
:
5964 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5970 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5972 uint16_t frag_offset
;
5976 uint16_t src_port
= 0;
5977 uint16_t dst_port
= 0;
5979 ip_filter_rulet
*rule
;
5981 if (len
< 20) // up to end of destination address
5984 if ((*buf
>> 4) != 4) // IPv4
5987 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5989 src_ip
= *(in_addr_t
*) (buf
+ 12);
5990 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5992 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5994 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5995 if (len
< l
+ 4) // ports
5998 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
5999 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6000 if (proto
== IPPROTO_TCP
)
6002 if (len
< l
+ 14) // flags
6005 flags
= buf
[l
+ 13] & 0x3f;
6009 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6011 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6014 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6015 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6018 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6019 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6024 // layer 4 deny rules are skipped
6025 if (rule
->action
== FILTER_ACTION_DENY
&&
6026 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6034 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6036 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6039 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6042 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6043 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6050 return rule
->action
== FILTER_ACTION_PERMIT
;