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 sessionidt members
[MAXBUNDLESES
];
1467 bundleidt bid
= session
[s
].bundle
;
1468 bundlet
*b
= &bundle
[bid
];
1469 uint32_t num_of_links
, nb_opened
;
1472 num_of_links
= b
->num_of_links
;
1474 for (i
= 0;i
< num_of_links
;i
++)
1477 if (session
[s
].ppp
.lcp
== Opened
)
1479 members
[nb_opened
] = s
;
1486 LOG(2, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1490 num_of_links
= nb_opened
;
1491 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1492 s
= members
[b
->current_ses
];
1493 t
= session
[s
].tunnel
;
1496 if ((num_of_links
> 1) && (len
> MINFRAGLEN
))
1498 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1500 //for rotate traffic among the member links
1501 uint32_t divisor
= num_of_links
;
1505 // Partition the packet to "num_of_links" fragments
1506 uint32_t fraglen
= len
/ divisor
;
1507 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1508 uint32_t remain
= len
;
1510 // send the first packet
1511 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1513 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1516 update_session_out_stat(s
, sp
, fraglen
);
1519 while (remain
> last_fraglen
)
1521 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1522 s
= members
[b
->current_ses
];
1523 t
= session
[s
].tunnel
;
1525 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1526 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1528 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1529 update_session_out_stat(s
, sp
, fraglen
);
1532 // send the last fragment
1533 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1534 s
= members
[b
->current_ses
];
1535 t
= session
[s
].tunnel
;
1537 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1538 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1540 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1541 update_session_out_stat(s
, sp
, remain
);
1542 if (remain
!= last_fraglen
)
1543 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1546 // Send it as one frame
1547 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1549 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1550 update_session_out_stat(s
, sp
, len
);
1555 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1557 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1558 update_session_out_stat(s
, sp
, len
);
1561 // Snooping this session, send it to intercept box
1562 if (sp
->snoop_ip
&& sp
->snoop_port
)
1563 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1568 // process outgoing (to tunnel) IPv6
1570 static void processipv6out(uint8_t * buf
, int len
)
1576 struct in6_addr ip6
;
1578 uint8_t *data
= buf
; // Keep a copy of the originals.
1581 uint8_t b
[MAXETHER
+ 20];
1583 CSTAT(processipv6out
);
1585 if (len
< MIN_IP_SIZE
)
1587 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1588 STAT(tunnel_tx_errors
);
1591 if (len
>= MAXETHER
)
1593 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1594 STAT(tunnel_tx_errors
);
1598 // Skip the tun header
1602 // Got an IP header now
1603 if (*(uint8_t *)(buf
) >> 4 != 6)
1605 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1609 ip6
= *(struct in6_addr
*)(buf
+24);
1610 s
= sessionbyipv6(ip6
);
1614 ip
= *(uint32_t *)(buf
+ 32);
1615 s
= sessionbyip(ip
);
1620 // Is this a packet for a session that doesn't exist?
1621 static int rate
= 0; // Number of ICMP packets we've sent this second.
1622 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1624 if (last
!= time_now
)
1630 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1632 // FIXME: Should send icmp6 host unreachable
1636 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1638 bundleidt bid
= session
[s
].bundle
;
1639 bundlet
*b
= &bundle
[bid
];
1641 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1642 s
= b
->members
[b
->current_ses
];
1643 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1645 t
= session
[s
].tunnel
;
1647 sp
->last_data
= time_now
;
1649 // FIXME: add DoS prevention/filters?
1653 // Are we throttling this session?
1654 if (config
->cluster_iam_master
)
1655 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1657 master_throttle_packet(sp
->tbf_out
, data
, size
);
1660 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1662 // We are walled-gardening this
1663 master_garden_packet(s
, data
, size
);
1667 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1669 // Add on L2TP header
1671 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1673 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1676 // Snooping this session, send it to intercept box
1677 if (sp
->snoop_ip
&& sp
->snoop_port
)
1678 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1680 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1681 sp
->cout_delta
+= len
;
1685 sess_local
[s
].cout
+= len
; // To send to master..
1686 sess_local
[s
].pout
++;
1690 // Helper routine for the TBF filters.
1691 // Used to send queued data in to the user!
1693 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1698 uint8_t b
[MAXETHER
+ 20];
1700 if (len
< 0 || len
> MAXETHER
)
1702 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1706 // Skip the tun header
1713 t
= session
[s
].tunnel
;
1716 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1718 // Add on L2TP header
1720 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1722 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1725 // Snooping this session.
1726 if (sp
->snoop_ip
&& sp
->snoop_port
)
1727 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1729 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1730 sp
->cout_delta
+= len
;
1734 sess_local
[s
].cout
+= len
; // To send to master..
1735 sess_local
[s
].pout
++;
1738 // add an AVP (16 bit)
1739 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1741 uint16_t l
= (m
? 0x8008 : 0x0008);
1742 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1743 c
->buf16
[c
->length
/2 + 1] = htons(0);
1744 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1745 c
->buf16
[c
->length
/2 + 3] = htons(val
);
1749 // add an AVP (32 bit)
1750 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1752 uint16_t l
= (m
? 0x800A : 0x000A);
1753 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1754 c
->buf16
[c
->length
/2 + 1] = htons(0);
1755 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1756 *(uint32_t *) &c
->buf
[c
->length
+ 6] = htonl(val
);
1760 // add an AVP (string)
1761 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1763 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1764 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1765 c
->buf16
[c
->length
/2 + 1] = htons(0);
1766 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1767 memcpy(&c
->buf
[c
->length
+ 6], val
, strlen(val
));
1768 c
->length
+= 6 + strlen(val
);
1772 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1774 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1775 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1776 c
->buf16
[c
->length
/2 + 1] = htons(0);
1777 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1778 memcpy(&c
->buf
[c
->length
+ 6], val
, len
);
1779 c
->length
+= 6 + len
;
1782 // new control connection
1783 static controlt
*controlnew(uint16_t mtype
)
1787 c
= malloc(sizeof(controlt
));
1791 controlfree
= c
->next
;
1795 c
->buf16
[0] = htons(0xC802); // flags/ver
1797 control16(c
, 0, mtype
, 1);
1801 // send zero block if nothing is waiting
1803 static void controlnull(tunnelidt t
)
1806 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1809 buf
[0] = htons(0xC802); // flags/ver
1810 buf
[1] = htons(12); // length
1811 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1812 buf
[3] = htons(0); // session
1813 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1814 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1815 tunnelsend((uint8_t *)buf
, 12, t
);
1818 // add a control message to a tunnel, and send if within window
1819 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1821 c
->buf16
[1] = htons(c
->length
); // length
1822 c
->buf16
[2] = htons(tunnel
[t
].far
); // tunnel
1823 c
->buf16
[3] = htons(far
); // session
1824 c
->buf16
[4] = htons(tunnel
[t
].ns
); // sequence
1825 tunnel
[t
].ns
++; // advance sequence
1826 // link in message in to queue
1827 if (tunnel
[t
].controlc
)
1828 tunnel
[t
].controle
->next
= c
;
1830 tunnel
[t
].controls
= c
;
1832 tunnel
[t
].controle
= c
;
1833 tunnel
[t
].controlc
++;
1835 // send now if space in window
1836 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1838 tunnel
[t
].try = 0; // first send
1839 tunnelsend(c
->buf
, c
->length
, t
);
1844 // Throttle or Unthrottle a session
1846 // Throttle the data from/to through a session to no more than
1847 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1850 // If either value is -1, the current value is retained for that
1853 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1855 if (!session
[s
].opened
)
1856 return; // No-one home.
1858 if (!*session
[s
].user
)
1859 return; // User not logged in
1863 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1864 if (session
[s
].tbf_in
)
1865 free_tbf(session
[s
].tbf_in
);
1868 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1870 session
[s
].tbf_in
= 0;
1872 session
[s
].throttle_in
= rate_in
;
1877 int bytes
= rate_out
* 1024 / 8;
1878 if (session
[s
].tbf_out
)
1879 free_tbf(session
[s
].tbf_out
);
1882 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1884 session
[s
].tbf_out
= 0;
1886 session
[s
].throttle_out
= rate_out
;
1890 // add/remove filters from session (-1 = no change)
1891 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1893 if (!session
[s
].opened
)
1894 return; // No-one home.
1896 if (!*session
[s
].user
)
1897 return; // User not logged in
1900 if (filter_in
> MAXFILTER
) filter_in
= -1;
1901 if (filter_out
> MAXFILTER
) filter_out
= -1;
1902 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1903 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1907 if (session
[s
].filter_in
)
1908 ip_filters
[session
[s
].filter_in
- 1].used
--;
1911 ip_filters
[filter_in
- 1].used
++;
1913 session
[s
].filter_in
= filter_in
;
1916 if (filter_out
>= 0)
1918 if (session
[s
].filter_out
)
1919 ip_filters
[session
[s
].filter_out
- 1].used
--;
1922 ip_filters
[filter_out
- 1].used
++;
1924 session
[s
].filter_out
= filter_out
;
1928 // start tidy shutdown of session
1929 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1931 int walled_garden
= session
[s
].walled_garden
;
1932 bundleidt b
= session
[s
].bundle
;
1933 //delete routes only for last session in bundle (in case of MPPP)
1934 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1936 CSTAT(sessionshutdown
);
1938 if (!session
[s
].opened
)
1940 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1941 return; // not a live session
1944 if (!session
[s
].die
)
1946 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1947 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1948 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1949 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1952 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1954 // RADIUS Stop message
1955 uint16_t r
= radiusnew(s
);
1958 // stop, if not already trying
1959 if (radius
[r
].state
!= RADIUSSTOP
)
1961 radius
[r
].term_cause
= term_cause
;
1962 radius
[r
].term_msg
= reason
;
1963 radiussend(r
, RADIUSSTOP
);
1967 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1969 // Save counters to dump to accounting file
1970 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1971 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1975 { // IP allocated, clear and unroute
1978 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1980 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
1981 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
1984 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
1985 session
[s
].route
[r
].ip
= 0;
1988 if (session
[s
].ip_pool_index
== -1) // static ip
1990 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1996 // unroute IPv6, if setup
1997 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
1998 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2002 // This session was part of a bundle
2003 bundle
[b
].num_of_links
--;
2004 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2005 if(bundle
[b
].num_of_links
== 0)
2008 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2012 // Adjust the members array to accomodate the new change
2013 uint8_t mem_num
= 0;
2014 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2015 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2018 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2019 if(bundle
[b
].members
[ml
] == s
)
2024 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2025 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2027 // If the killed session is the first of the bundle,
2028 // the new first session must be stored in the cache_ipmap
2029 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2032 sessionidt new_s
= bundle
[b
].members
[0];
2035 // Add the route for this session.
2036 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2041 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2042 ip
= session
[new_s
].route
[r
].ip
;
2044 if (!prefixlen
) prefixlen
= 32;
2045 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2047 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2048 cache_ipmap(i
, new_s
);
2050 cache_ipmap(session
[new_s
].ip
, new_s
);
2053 if (session
[new_s
].ipv6prefixlen
)
2054 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2059 cluster_send_bundle(b
);
2063 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2064 throttle_session(s
, 0, 0);
2068 controlt
*c
= controlnew(14); // sending CDN
2072 buf
[0] = htons(cdn_result
);
2073 buf
[1] = htons(cdn_error
);
2074 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2077 control16(c
, 1, cdn_result
, 1);
2079 control16(c
, 14, s
, 1); // assigned session (our end)
2080 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2083 // update filter refcounts
2084 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2085 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2088 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2089 sess_local
[s
].lcp
.restart
= 0;
2090 sess_local
[s
].ipcp
.restart
= 0;
2091 sess_local
[s
].ipv6cp
.restart
= 0;
2092 sess_local
[s
].ccp
.restart
= 0;
2094 cluster_send_session(s
);
2097 void sendipcp(sessionidt s
, tunnelidt t
)
2099 uint8_t buf
[MAXETHER
];
2103 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2105 if (!session
[s
].unique_id
)
2107 if (!++last_id
) ++last_id
; // skip zero
2108 session
[s
].unique_id
= last_id
;
2111 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2115 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2116 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2117 q
[4] = 3; // ip address option
2118 q
[5] = 6; // option length
2119 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2120 config
->bind_address
? config
->bind_address
:
2121 my_address
; // send my IP
2123 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2124 restart_timer(s
, ipcp
);
2127 void sendipv6cp(sessionidt s
, tunnelidt t
)
2129 uint8_t buf
[MAXETHER
];
2133 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2135 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2139 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2140 // only send one type
2142 *(uint16_t *) (q
+ 2) = htons(14);
2143 q
[4] = 1; // interface identifier option
2144 q
[5] = 10; // option length
2145 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2146 *(uint32_t *) (q
+ 10) = 0;
2149 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2150 restart_timer(s
, ipv6cp
);
2153 static void sessionclear(sessionidt s
)
2155 memset(&session
[s
], 0, sizeof(session
[s
]));
2156 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2157 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2159 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2160 session
[s
].next
= sessionfree
;
2164 // kill a session now
2165 void sessionkill(sessionidt s
, char *reason
)
2169 if (!session
[s
].opened
) // not alive
2172 if (session
[s
].next
)
2174 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2178 if (!session
[s
].die
)
2179 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2181 if (sess_local
[s
].radius
)
2182 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2184 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2186 cluster_send_session(s
);
2189 static void tunnelclear(tunnelidt t
)
2192 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2193 tunnel
[t
].state
= TUNNELFREE
;
2196 static void bundleclear(bundleidt b
)
2199 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2200 bundle
[b
].state
= BUNDLEFREE
;
2203 // kill a tunnel now
2204 static void tunnelkill(tunnelidt t
, char *reason
)
2211 tunnel
[t
].state
= TUNNELDIE
;
2213 // free control messages
2214 while ((c
= tunnel
[t
].controls
))
2216 controlt
* n
= c
->next
;
2217 tunnel
[t
].controls
= n
;
2218 tunnel
[t
].controlc
--;
2219 c
->next
= controlfree
;
2223 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2224 if (session
[s
].tunnel
== t
)
2225 sessionkill(s
, reason
);
2229 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2230 cli_tunnel_actions
[t
].action
= 0;
2231 cluster_send_tunnel(t
);
2234 // shut down a tunnel cleanly
2235 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2239 CSTAT(tunnelshutdown
);
2241 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2243 // never set up, can immediately kill
2244 tunnelkill(t
, reason
);
2247 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2250 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2251 if (session
[s
].tunnel
== t
)
2252 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2254 tunnel
[t
].state
= TUNNELDIE
;
2255 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2256 cluster_send_tunnel(t
);
2257 // TBA - should we wait for sessions to stop?
2260 controlt
*c
= controlnew(4); // sending StopCCN
2265 buf
[0] = htons(result
);
2266 buf
[1] = htons(error
);
2269 int m
= strlen(msg
);
2270 if (m
+ 4 > sizeof(buf
))
2271 m
= sizeof(buf
) - 4;
2273 memcpy(buf
+2, msg
, m
);
2277 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2280 control16(c
, 1, result
, 1);
2282 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2283 controladd(c
, 0, t
); // send the message
2287 // read and process packet on tunnel (UDP)
2288 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2290 uint8_t *chapresponse
= NULL
;
2291 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2292 uint8_t *p
= buf
+ 2;
2299 LOG_HEX(5, "UDP Data", buf
, len
);
2300 STAT(tunnel_rx_packets
);
2301 INC_STAT(tunnel_rx_bytes
, len
);
2304 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2305 STAT(tunnel_rx_errors
);
2308 if ((buf
[1] & 0x0F) != 2)
2310 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2311 STAT(tunnel_rx_errors
);
2316 l
= ntohs(*(uint16_t *) p
);
2319 t
= ntohs(*(uint16_t *) p
);
2321 s
= ntohs(*(uint16_t *) p
);
2323 if (s
>= MAXSESSION
)
2325 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2326 STAT(tunnel_rx_errors
);
2331 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2332 STAT(tunnel_rx_errors
);
2337 ns
= ntohs(*(uint16_t *) p
);
2339 nr
= ntohs(*(uint16_t *) p
);
2344 uint16_t o
= ntohs(*(uint16_t *) p
);
2349 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2350 STAT(tunnel_rx_errors
);
2355 // used to time out old tunnels
2356 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2357 tunnel
[t
].lastrec
= time_now
;
2361 uint16_t message
= 0xFFFF; // message type
2363 uint8_t mandatory
= 0;
2364 uint16_t asession
= 0; // assigned session
2365 uint32_t amagic
= 0; // magic number
2366 uint8_t aflags
= 0; // flags from last LCF
2367 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2368 char called
[MAXTEL
] = ""; // called number
2369 char calling
[MAXTEL
] = ""; // calling number
2371 if (!config
->cluster_iam_master
)
2373 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2377 // control messages must have bits 0x80|0x40|0x08
2378 // (type, length and sequence) set, and bits 0x02|0x01
2379 // (offset and priority) clear
2380 if ((*buf
& 0xCB) != 0xC8)
2382 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2383 STAT(tunnel_rx_errors
);
2387 // check for duplicate tunnel open message
2393 // Is this a duplicate of the first packet? (SCCRQ)
2395 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2397 if (tunnel
[i
].state
!= TUNNELOPENING
||
2398 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2399 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2402 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2407 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2408 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2410 // if no tunnel specified, assign one
2413 if (!(t
= new_tunnel()))
2415 LOG(1, 0, 0, "No more tunnels\n");
2416 STAT(tunnel_overflow
);
2420 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2421 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2422 tunnel
[t
].window
= 4; // default window
2423 STAT(tunnel_created
);
2424 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2425 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2428 // If the 'ns' just received is not the 'nr' we're
2429 // expecting, just send an ack and drop it.
2431 // if 'ns' is less, then we got a retransmitted packet.
2432 // if 'ns' is greater than missed a packet. Either way
2433 // we should ignore it.
2434 if (ns
!= tunnel
[t
].nr
)
2436 // is this the sequence we were expecting?
2437 STAT(tunnel_rx_errors
);
2438 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2439 t
, ns
, tunnel
[t
].nr
);
2441 if (l
) // Is this not a ZLB?
2446 // check sequence of this message
2448 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2449 // some to clear maybe?
2450 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2452 controlt
*c
= tunnel
[t
].controls
;
2453 tunnel
[t
].controls
= c
->next
;
2454 tunnel
[t
].controlc
--;
2455 c
->next
= controlfree
;
2458 tunnel
[t
].try = 0; // we have progress
2461 // receiver advance (do here so quoted correctly in any sends below)
2462 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2463 if (skip
< 0) skip
= 0;
2464 if (skip
< tunnel
[t
].controlc
)
2466 // some control packets can now be sent that were previous stuck out of window
2467 int tosend
= tunnel
[t
].window
- skip
;
2468 controlt
*c
= tunnel
[t
].controls
;
2476 tunnel
[t
].try = 0; // first send
2477 tunnelsend(c
->buf
, c
->length
, t
);
2482 if (!tunnel
[t
].controlc
)
2483 tunnel
[t
].retry
= 0; // caught up
2486 { // if not a null message
2491 // Default disconnect cause/message on receipt of CDN. Set to
2492 // more specific value from attribute 1 (result code) or 46
2493 // (disconnect cause) if present below.
2494 int disc_cause_set
= 0;
2495 int disc_cause
= TERM_NAS_REQUEST
;
2496 char const *disc_reason
= "Closed (Received CDN).";
2499 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2501 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2508 LOG(1, s
, t
, "Invalid length in AVP\n");
2509 STAT(tunnel_rx_errors
);
2514 if (flags
& 0x3C) // reserved bits, should be clear
2516 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2518 result
= 2; // general error
2519 error
= 3; // reserved field non-zero
2524 if (*(uint16_t *) (b
))
2526 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2528 result
= 2; // general error
2529 error
= 6; // generic vendor-specific error
2530 msg
= "unsupported vendor-specific";
2534 mtype
= ntohs(*(uint16_t *) (b
));
2542 // handle hidden AVPs
2543 if (!*config
->l2tp_secret
)
2545 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2547 result
= 2; // general error
2548 error
= 6; // generic vendor-specific error
2549 msg
= "secret not specified";
2552 if (!session
[s
].random_vector_length
)
2554 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2556 result
= 2; // general error
2557 error
= 6; // generic
2558 msg
= "no random vector";
2563 LOG(2, s
, t
, "Short hidden AVP.\n");
2565 result
= 2; // general error
2566 error
= 2; // length is wrong
2572 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2574 orig_len
= ntohs(*(uint16_t *) b
);
2575 if (orig_len
> n
+ 2)
2577 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2581 result
= 2; // general error
2582 error
= 2; // length is wrong
2591 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2592 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2596 case 0: // message type
2597 message
= ntohs(*(uint16_t *) b
);
2598 mandatory
= flags
& 0x80;
2599 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2601 case 1: // result code
2603 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2604 char const *resdesc
= "(unknown)";
2605 char const *errdesc
= NULL
;
2610 resdesc
= l2tp_stopccn_result_code(rescode
);
2611 cause
= TERM_LOST_SERVICE
;
2613 else if (message
== 14)
2615 resdesc
= l2tp_cdn_result_code(rescode
);
2617 cause
= TERM_LOST_CARRIER
;
2619 cause
= TERM_ADMIN_RESET
;
2622 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2625 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2626 errdesc
= l2tp_error_code(errcode
);
2627 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2630 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2632 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2634 disc_cause_set
= mtype
;
2635 disc_reason
= errdesc
? errdesc
: resdesc
;
2642 case 2: // protocol version
2644 version
= ntohs(*(uint16_t *) (b
));
2645 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2646 if (version
&& version
!= 0x0100)
2647 { // allow 0.0 and 1.0
2648 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2650 result
= 5; // unspported protocol version
2651 error
= 0x0100; // supported version
2657 case 3: // framing capabilities
2659 case 4: // bearer capabilities
2661 case 5: // tie breaker
2662 // We never open tunnels, so we don't care about tie breakers
2664 case 6: // firmware revision
2666 case 7: // host name
2667 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2668 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2669 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2670 // TBA - to send to RADIUS
2672 case 8: // vendor name
2673 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2674 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2675 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2677 case 9: // assigned tunnel
2678 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2679 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2681 case 10: // rx window
2682 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2683 if (!tunnel
[t
].window
)
2684 tunnel
[t
].window
= 1; // window of 0 is silly
2685 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2687 case 11: // Challenge
2689 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2690 build_chap_response(b
, 2, n
, &chapresponse
);
2693 case 13: // Response
2694 // Why did they send a response? We never challenge.
2695 LOG(2, s
, t
, " received unexpected challenge response\n");
2698 case 14: // assigned session
2699 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2700 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2702 case 15: // call serial number
2703 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2705 case 18: // bearer type
2706 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2709 case 19: // framing type
2710 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2713 case 21: // called number
2714 memset(called
, 0, sizeof(called
));
2715 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2716 LOG(4, s
, t
, " Called <%s>\n", called
);
2718 case 22: // calling number
2719 memset(calling
, 0, sizeof(calling
));
2720 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2721 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2725 case 24: // tx connect speed
2728 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2732 // AS5300s send connect speed as a string
2734 memset(tmp
, 0, sizeof(tmp
));
2735 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2736 session
[s
].tx_connect_speed
= atol(tmp
);
2738 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2740 case 38: // rx connect speed
2743 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2747 // AS5300s send connect speed as a string
2749 memset(tmp
, 0, sizeof(tmp
));
2750 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2751 session
[s
].rx_connect_speed
= atol(tmp
);
2753 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2755 case 25: // Physical Channel ID
2757 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2758 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2761 case 29: // Proxy Authentication Type
2763 uint16_t atype
= ntohs(*(uint16_t *)b
);
2764 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2767 case 30: // Proxy Authentication Name
2770 memset(authname
, 0, sizeof(authname
));
2771 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2772 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2776 case 31: // Proxy Authentication Challenge
2778 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2781 case 32: // Proxy Authentication ID
2783 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2784 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2787 case 33: // Proxy Authentication Response
2788 LOG(4, s
, t
, " Proxy Auth Response\n");
2790 case 27: // last sent lcp
2791 { // find magic number
2792 uint8_t *p
= b
, *e
= p
+ n
;
2793 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2795 if (*p
== 5 && p
[1] == 6) // Magic-Number
2796 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2797 else if (*p
== 7) // Protocol-Field-Compression
2798 aflags
|= SESSION_PFC
;
2799 else if (*p
== 8) // Address-and-Control-Field-Compression
2800 aflags
|= SESSION_ACFC
;
2805 case 28: // last recv lcp confreq
2807 case 26: // Initial Received LCP CONFREQ
2809 case 39: // seq required - we control it as an LNS anyway...
2811 case 36: // Random Vector
2812 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2813 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2814 if (n
> sizeof(session
[s
].random_vector
))
2815 n
= sizeof(session
[s
].random_vector
);
2816 memcpy(session
[s
].random_vector
, b
, n
);
2817 session
[s
].random_vector_length
= n
;
2819 case 46: // ppp disconnect cause
2822 uint16_t code
= ntohs(*(uint16_t *) b
);
2823 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2824 uint8_t dir
= *(b
+ 4);
2826 LOG(4, s
, t
, " PPP disconnect cause "
2827 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2828 code
, proto
, dir
, n
- 5, b
+ 5);
2830 disc_cause_set
= mtype
;
2834 case 1: // admin disconnect
2835 disc_cause
= TERM_ADMIN_RESET
;
2836 disc_reason
= "Administrative disconnect";
2838 case 3: // lcp terminate
2839 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2840 disc_cause
= TERM_USER_REQUEST
;
2841 disc_reason
= "Normal disconnection";
2843 case 4: // compulsory encryption unavailable
2844 if (dir
!= 1) break; // 1=refused by peer, 2=local
2845 disc_cause
= TERM_USER_ERROR
;
2846 disc_reason
= "Compulsory encryption refused";
2848 case 5: // lcp: fsm timeout
2849 disc_cause
= TERM_PORT_ERROR
;
2850 disc_reason
= "LCP: FSM timeout";
2852 case 6: // lcp: no recognisable lcp packets received
2853 disc_cause
= TERM_PORT_ERROR
;
2854 disc_reason
= "LCP: no recognisable LCP packets";
2856 case 7: // lcp: magic-no error (possibly looped back)
2857 disc_cause
= TERM_PORT_ERROR
;
2858 disc_reason
= "LCP: magic-no error (possible loop)";
2860 case 8: // lcp: echo request timeout
2861 disc_cause
= TERM_PORT_ERROR
;
2862 disc_reason
= "LCP: echo request timeout";
2864 case 13: // auth: fsm timeout
2865 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2866 disc_reason
= "Authentication: FSM timeout";
2868 case 15: // auth: unacceptable auth protocol
2869 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2870 disc_reason
= "Unacceptable authentication protocol";
2872 case 16: // auth: authentication failed
2873 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2874 disc_reason
= "Authentication failed";
2876 case 17: // ncp: fsm timeout
2877 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2878 disc_reason
= "NCP: FSM timeout";
2880 case 18: // ncp: no ncps available
2881 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2882 disc_reason
= "NCP: no NCPs available";
2884 case 19: // ncp: failure to converge on acceptable address
2885 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2886 disc_reason
= (dir
== 1)
2887 ? "NCP: too many Configure-Naks received from peer"
2888 : "NCP: too many Configure-Naks sent to peer";
2890 case 20: // ncp: user not permitted to use any address
2891 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2892 disc_reason
= (dir
== 1)
2893 ? "NCP: local link address not acceptable to peer"
2894 : "NCP: remote link address not acceptable";
2901 static char e
[] = "unknown AVP 0xXXXX";
2902 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2904 result
= 2; // general error
2905 error
= 8; // unknown mandatory AVP
2906 sprintf((msg
= e
) + 14, "%04x", mtype
);
2913 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2917 case 1: // SCCRQ - Start Control Connection Request
2918 tunnel
[t
].state
= TUNNELOPENING
;
2919 if (main_quit
!= QUIT_SHUTDOWN
)
2921 controlt
*c
= controlnew(2); // sending SCCRP
2922 control16(c
, 2, version
, 1); // protocol version
2923 control32(c
, 3, 3, 1); // framing
2924 controls(c
, 7, hostname
, 1); // host name
2925 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2926 control16(c
, 9, t
, 1); // assigned tunnel
2927 controladd(c
, 0, t
); // send the resply
2931 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2935 tunnel
[t
].state
= TUNNELOPEN
;
2936 tunnel
[t
].lastrec
= time_now
;
2939 tunnel
[t
].state
= TUNNELOPEN
;
2940 tunnel
[t
].lastrec
= time_now
;
2941 controlnull(t
); // ack
2944 controlnull(t
); // ack
2945 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2948 controlnull(t
); // simply ACK
2960 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2962 controlt
*c
= controlnew(11); // ICRP
2965 sessionfree
= session
[s
].next
;
2966 memset(&session
[s
], 0, sizeof(session
[s
]));
2968 if (s
> config
->cluster_highest_sessionid
)
2969 config
->cluster_highest_sessionid
= s
;
2971 session
[s
].opened
= time_now
;
2972 session
[s
].tunnel
= t
;
2973 session
[s
].far
= asession
;
2974 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2975 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2976 control16(c
, 14, s
, 1); // assigned session
2977 controladd(c
, asession
, t
); // send the reply
2979 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2980 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2982 session
[s
].ppp
.phase
= Establish
;
2983 session
[s
].ppp
.lcp
= Starting
;
2985 STAT(session_created
);
2990 controlt
*c
= controlnew(14); // CDN
2993 STAT(session_overflow
);
2994 LOG(1, 0, t
, "No free sessions\n");
2995 control16(c
, 1, 4, 0); // temporary lack of resources
2998 control16(c
, 1, 2, 7); // shutting down, try another
3000 controladd(c
, asession
, t
); // send the message
3007 if (amagic
== 0) amagic
= time_now
;
3008 session
[s
].magic
= amagic
; // set magic number
3009 session
[s
].flags
= aflags
; // set flags received
3010 session
[s
].mru
= PPPoE_MRU
; // default
3011 controlnull(t
); // ack
3014 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3015 sess_local
[s
].ppp_mru
= MRU
;
3017 // Set multilink options before sending initial LCP packet
3018 sess_local
[s
].mp_mrru
= 1614;
3019 sess_local
[s
].mp_epdis
= ntohl(config
->bind_address
? config
->bind_address
: my_address
);
3022 change_state(s
, lcp
, RequestSent
);
3026 controlnull(t
); // ack
3027 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3030 LOG(1, s
, t
, "Missing message type\n");
3033 STAT(tunnel_rx_errors
);
3035 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3037 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3040 if (chapresponse
) free(chapresponse
);
3041 cluster_send_tunnel(t
);
3045 LOG(4, s
, t
, " Got a ZLB ack\n");
3052 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3053 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3054 { // HDLC address header, discard
3060 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3061 STAT(tunnel_rx_errors
);
3071 proto
= ntohs(*(uint16_t *) p
);
3076 if (s
&& !session
[s
].opened
) // Is something wrong??
3078 if (!config
->cluster_iam_master
)
3080 // Pass it off to the master to deal with..
3081 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3086 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3087 STAT(tunnel_rx_errors
);
3091 if (proto
== PPPPAP
)
3093 session
[s
].last_packet
= time_now
;
3094 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3095 processpap(s
, t
, p
, l
);
3097 else if (proto
== PPPCHAP
)
3099 session
[s
].last_packet
= time_now
;
3100 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3101 processchap(s
, t
, p
, l
);
3103 else if (proto
== PPPLCP
)
3105 session
[s
].last_packet
= time_now
;
3106 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3107 processlcp(s
, t
, p
, l
);
3109 else if (proto
== PPPIPCP
)
3111 session
[s
].last_packet
= time_now
;
3112 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3113 processipcp(s
, t
, p
, l
);
3115 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3117 session
[s
].last_packet
= time_now
;
3118 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3119 processipv6cp(s
, t
, p
, l
);
3121 else if (proto
== PPPCCP
)
3123 session
[s
].last_packet
= time_now
;
3124 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3125 processccp(s
, t
, p
, l
);
3127 else if (proto
== PPPIP
)
3131 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3132 return; // closing session, PPP not processed
3135 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3136 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3138 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3142 processipin(s
, t
, p
, l
);
3144 else if (proto
== PPPMP
)
3148 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3149 return; // closing session, PPP not processed
3152 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3153 if (!config
->cluster_iam_master
)
3155 // The fragments reconstruction is managed by the Master.
3156 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3160 processmpin(s
, t
, p
, l
);
3162 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3166 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3167 return; // closing session, PPP not processed
3170 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3171 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3173 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3177 processipv6in(s
, t
, p
, l
);
3179 else if (session
[s
].ppp
.lcp
== Opened
)
3181 session
[s
].last_packet
= time_now
;
3182 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3183 protoreject(s
, t
, p
, l
, proto
);
3187 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3188 proto
, ppp_state(session
[s
].ppp
.lcp
));
3193 // read and process packet on tun
3194 static void processtun(uint8_t * buf
, int len
)
3196 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3197 STAT(tun_rx_packets
);
3198 INC_STAT(tun_rx_bytes
, len
);
3206 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3207 STAT(tun_rx_errors
);
3211 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3212 processipout(buf
, len
);
3213 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3214 && config
->ipv6_prefix
.s6_addr
[0])
3215 processipv6out(buf
, len
);
3220 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3221 // that we look at the whole of the tunnel, radius and session tables
3223 static void regular_cleanups(double period
)
3225 // Next tunnel, radius and session to check for actions on.
3226 static tunnelidt t
= 0;
3228 static sessionidt s
= 0;
3241 // divide up tables into slices based on the last run
3242 t_slice
= config
->cluster_highest_tunnelid
* period
;
3243 r_slice
= (MAXRADIUS
- 1) * period
;
3244 s_slice
= config
->cluster_highest_sessionid
* period
;
3248 else if (t_slice
> config
->cluster_highest_tunnelid
)
3249 t_slice
= config
->cluster_highest_tunnelid
;
3253 else if (r_slice
> (MAXRADIUS
- 1))
3254 r_slice
= MAXRADIUS
- 1;
3258 else if (s_slice
> config
->cluster_highest_sessionid
)
3259 s_slice
= config
->cluster_highest_sessionid
;
3261 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3263 for (i
= 0; i
< t_slice
; i
++)
3266 if (t
> config
->cluster_highest_tunnelid
)
3269 // check for expired tunnels
3270 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3272 STAT(tunnel_timeout
);
3273 tunnelkill(t
, "Expired");
3277 // check for message resend
3278 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3280 // resend pending messages as timeout on reply
3281 if (tunnel
[t
].retry
<= TIME
)
3283 controlt
*c
= tunnel
[t
].controls
;
3284 uint16_t w
= tunnel
[t
].window
;
3285 tunnel
[t
].try++; // another try
3286 if (tunnel
[t
].try > 5)
3287 tunnelkill(t
, "Timeout on control message"); // game over
3291 tunnelsend(c
->buf
, c
->length
, t
);
3299 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3301 controlt
*c
= controlnew(6); // sending HELLO
3302 controladd(c
, 0, t
); // send the message
3303 LOG(3, 0, t
, "Sending HELLO message\n");
3307 // Check for tunnel changes requested from the CLI
3308 if ((a
= cli_tunnel_actions
[t
].action
))
3310 cli_tunnel_actions
[t
].action
= 0;
3311 if (a
& CLI_TUN_KILL
)
3313 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3314 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3320 for (i
= 0; i
< r_slice
; i
++)
3326 if (!radius
[r
].state
)
3329 if (radius
[r
].retry
<= TIME
)
3336 for (i
= 0; i
< s_slice
; i
++)
3339 if (s
> config
->cluster_highest_sessionid
)
3342 if (!session
[s
].opened
) // Session isn't in use
3345 // check for expired sessions
3348 if (session
[s
].die
<= TIME
)
3350 sessionkill(s
, "Expired");
3357 if (sess_local
[s
].lcp
.restart
<= time_now
)
3359 int next_state
= session
[s
].ppp
.lcp
;
3360 switch (session
[s
].ppp
.lcp
)
3364 next_state
= RequestSent
;
3367 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3369 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3370 sendlcp(s
, session
[s
].tunnel
);
3371 change_state(s
, lcp
, next_state
);
3375 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3376 STAT(session_timeout
);
3386 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3388 int next_state
= session
[s
].ppp
.ipcp
;
3389 switch (session
[s
].ppp
.ipcp
)
3393 next_state
= RequestSent
;
3396 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3398 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3399 sendipcp(s
, session
[s
].tunnel
);
3400 change_state(s
, ipcp
, next_state
);
3404 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3405 STAT(session_timeout
);
3415 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3417 int next_state
= session
[s
].ppp
.ipv6cp
;
3418 switch (session
[s
].ppp
.ipv6cp
)
3422 next_state
= RequestSent
;
3425 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3427 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3428 sendipv6cp(s
, session
[s
].tunnel
);
3429 change_state(s
, ipv6cp
, next_state
);
3433 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3434 change_state(s
, ipv6cp
, Stopped
);
3441 if (sess_local
[s
].ccp
.restart
<= time_now
)
3443 int next_state
= session
[s
].ppp
.ccp
;
3444 switch (session
[s
].ppp
.ccp
)
3448 next_state
= RequestSent
;
3451 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3453 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3454 sendccp(s
, session
[s
].tunnel
);
3455 change_state(s
, ccp
, next_state
);
3459 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3460 change_state(s
, ccp
, Stopped
);
3467 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3468 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3470 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3471 STAT(session_timeout
);
3476 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3477 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3478 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3480 uint8_t b
[MAXETHER
];
3482 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3486 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3487 *(uint16_t *)(q
+ 2) = htons(8); // Length
3488 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3490 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3491 (int)(time_now
- session
[s
].last_packet
));
3492 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3493 sess_local
[s
].last_echo
= time_now
;
3497 // Drop sessions who have reached session_timeout seconds
3498 if (session
[s
].session_timeout
)
3500 bundleidt bid
= session
[s
].bundle
;
3503 if (time_now
- bundle
[bid
].last_check
>= 1)
3505 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3506 bundle
[bid
].last_check
= time_now
;
3507 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3510 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3512 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3519 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3521 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3527 // Drop sessions who have reached idle_timeout seconds
3528 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3530 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3531 STAT(session_timeout
);
3536 // Check for actions requested from the CLI
3537 if ((a
= cli_session_actions
[s
].action
))
3541 cli_session_actions
[s
].action
= 0;
3542 if (a
& CLI_SESS_KILL
)
3544 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3545 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3546 a
= 0; // dead, no need to check for other actions
3550 if (a
& CLI_SESS_NOSNOOP
)
3552 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3553 session
[s
].snoop_ip
= 0;
3554 session
[s
].snoop_port
= 0;
3558 else if (a
& CLI_SESS_SNOOP
)
3560 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3561 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3562 cli_session_actions
[s
].snoop_port
);
3564 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3565 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3570 if (a
& CLI_SESS_NOTHROTTLE
)
3572 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3573 throttle_session(s
, 0, 0);
3577 else if (a
& CLI_SESS_THROTTLE
)
3579 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3580 cli_session_actions
[s
].throttle_in
,
3581 cli_session_actions
[s
].throttle_out
);
3583 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3588 if (a
& CLI_SESS_NOFILTER
)
3590 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3591 filter_session(s
, 0, 0);
3595 else if (a
& CLI_SESS_FILTER
)
3597 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3598 cli_session_actions
[s
].filter_in
,
3599 cli_session_actions
[s
].filter_out
);
3601 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3607 cluster_send_session(s
);
3610 // RADIUS interim accounting
3611 if (config
->radius_accounting
&& config
->radius_interim
> 0
3612 && session
[s
].ip
&& !session
[s
].walled_garden
3613 && !sess_local
[s
].radius
// RADIUS already in progress
3614 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3615 && session
[s
].flags
& SESSION_STARTED
)
3617 int rad
= radiusnew(s
);
3620 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3621 STAT(radius_overflow
);
3625 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3626 session
[s
].user
, session
[s
].unique_id
);
3628 radiussend(rad
, RADIUSINTERIM
);
3629 sess_local
[s
].last_interim
= time_now
;
3634 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3635 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3639 // Are we in the middle of a tunnel update, or radius
3642 static int still_busy(void)
3645 static clockt last_talked
= 0;
3646 static clockt start_busy_wait
= 0;
3649 static time_t stopped_bgp
= 0;
3654 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3656 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3657 if (bgp_peers
[i
].state
== Established
)
3658 bgp_stop(&bgp_peers
[i
]);
3660 stopped_bgp
= time_now
;
3662 if (!config
->cluster_iam_master
)
3664 // we don't want to become master
3665 cluster_send_ping(0);
3671 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3676 if (!config
->cluster_iam_master
)
3679 if (main_quit
== QUIT_SHUTDOWN
)
3681 static int dropped
= 0;
3686 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3687 for (i
= 1; i
< MAXTUNNEL
; i
++)
3688 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3689 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3695 if (start_busy_wait
== 0)
3696 start_busy_wait
= TIME
;
3698 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3700 if (!tunnel
[i
].controlc
)
3703 if (last_talked
!= TIME
)
3705 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3711 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3712 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3714 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3718 for (i
= 1; i
< MAXRADIUS
; i
++)
3720 if (radius
[i
].state
== RADIUSNULL
)
3722 if (radius
[i
].state
== RADIUSWAIT
)
3725 if (last_talked
!= TIME
)
3727 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3737 # include <sys/epoll.h>
3739 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3740 # include "fake_epoll.h"
3743 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3746 // additional polled fds
3748 # define EXTRA_FDS BGP_NUM_PEERS
3750 # define EXTRA_FDS 0
3753 // main loop - gets packets on tun or udp and processes them
3754 static void mainloop(void)
3758 clockt next_cluster_ping
= 0; // send initial ping immediately
3759 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3760 int maxevent
= sizeof(events
)/sizeof(*events
);
3762 if ((epollfd
= epoll_create(maxevent
)) < 0)
3764 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3768 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3769 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3771 /* setup our fds to poll for input */
3773 static struct event_data d
[BASE_FDS
];
3774 struct epoll_event e
;
3781 d
[i
].type
= FD_TYPE_CLI
;
3782 e
.data
.ptr
= &d
[i
++];
3783 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3786 d
[i
].type
= FD_TYPE_CLUSTER
;
3787 e
.data
.ptr
= &d
[i
++];
3788 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3790 d
[i
].type
= FD_TYPE_TUN
;
3791 e
.data
.ptr
= &d
[i
++];
3792 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3794 d
[i
].type
= FD_TYPE_UDP
;
3795 e
.data
.ptr
= &d
[i
++];
3796 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3798 d
[i
].type
= FD_TYPE_CONTROL
;
3799 e
.data
.ptr
= &d
[i
++];
3800 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3802 d
[i
].type
= FD_TYPE_DAE
;
3803 e
.data
.ptr
= &d
[i
++];
3804 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3806 d
[i
].type
= FD_TYPE_NETLINK
;
3807 e
.data
.ptr
= &d
[i
++];
3808 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3812 signal(SIGPIPE
, SIG_IGN
);
3813 bgp_setup(config
->as_number
);
3814 if (config
->bind_address
)
3815 bgp_add_route(config
->bind_address
, 0xffffffff);
3817 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3819 if (config
->neighbour
[i
].name
[0])
3820 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3821 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3822 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
3823 0); /* 0 = routing disabled */
3827 while (!main_quit
|| still_busy())
3837 config
->reload_config
++;
3840 if (config
->reload_config
)
3842 config
->reload_config
= 0;
3850 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3851 STAT(select_called
);
3856 if (errno
== EINTR
||
3857 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3860 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3866 struct sockaddr_in addr
;
3867 struct in_addr local
;
3872 int cluster_ready
= 0;
3875 int cluster_pkts
= 0;
3877 uint32_t bgp_events
[BGP_NUM_PEERS
];
3878 memset(bgp_events
, 0, sizeof(bgp_events
));
3881 for (c
= n
, i
= 0; i
< c
; i
++)
3883 struct event_data
*d
= events
[i
].data
.ptr
;
3887 case FD_TYPE_CLI
: // CLI connections
3891 alen
= sizeof(addr
);
3892 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3898 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3904 // these are handled below, with multiple interleaved reads
3905 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3906 case FD_TYPE_TUN
: tun_ready
++; break;
3907 case FD_TYPE_UDP
: udp_ready
++; break;
3909 case FD_TYPE_CONTROL
: // nsctl commands
3910 alen
= sizeof(addr
);
3911 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3912 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3916 case FD_TYPE_DAE
: // DAE requests
3917 alen
= sizeof(addr
);
3918 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3919 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3923 case FD_TYPE_RADIUS
: // RADIUS response
3924 alen
= sizeof(addr
);
3925 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3926 if (s
>= 0 && config
->cluster_iam_master
)
3928 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3929 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3930 processrad(buf
, s
, d
->index
);
3932 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3933 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3941 bgp_events
[d
->index
] = events
[i
].events
;
3946 case FD_TYPE_NETLINK
:
3948 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
3949 s
= netlink_recv(buf
, sizeof(buf
));
3950 if (nh
->nlmsg_type
== NLMSG_ERROR
)
3952 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
3955 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
3957 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
3962 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
3967 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
);
3973 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3978 bgp_process(bgp_events
);
3981 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3986 alen
= sizeof(addr
);
3987 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3989 processudp(buf
, s
, &addr
);
4002 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
4017 alen
= sizeof(addr
);
4018 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4020 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
4031 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4032 STAT(multi_read_used
);
4034 if (c
>= config
->multi_read_count
)
4036 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
4037 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
4039 STAT(multi_read_exceeded
);
4045 /* no event received, but timers could still have expired */
4046 bgp_process_peers_timers();
4051 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4053 // Log current traffic stats
4054 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4055 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4056 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4057 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4058 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4060 udp_tx
= udp_rx
= 0;
4061 udp_rx_pkt
= eth_rx_pkt
= 0;
4062 eth_tx
= eth_rx
= 0;
4065 if (config
->dump_speed
)
4066 printf("%s\n", config
->bandwidth
);
4068 // Update the internal time counter
4069 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4073 struct param_timer p
= { time_now
};
4074 run_plugins(PLUGIN_TIMER
, &p
);
4078 // Runs on every machine (master and slaves).
4079 if (next_cluster_ping
<= TIME
)
4081 // Check to see which of the cluster is still alive..
4083 cluster_send_ping(basetime
); // Only does anything if we're a slave
4084 cluster_check_master(); // ditto.
4086 cluster_heartbeat(); // Only does anything if we're a master.
4087 cluster_check_slaves(); // ditto.
4089 master_update_counts(); // If we're a slave, send our byte counters to our master.
4091 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4092 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4094 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4097 if (!config
->cluster_iam_master
)
4100 // Run token bucket filtering queue..
4101 // Only run it every 1/10th of a second.
4103 static clockt last_run
= 0;
4104 if (last_run
!= TIME
)
4111 // Handle timeouts, retries etc.
4113 static double last_clean
= 0;
4117 TIME
= now(&this_clean
);
4118 diff
= this_clean
- last_clean
;
4120 // Run during idle time (after we've handled
4121 // all incoming packets) or every 1/10th sec
4122 if (!more
|| diff
> 0.1)
4124 regular_cleanups(diff
);
4125 last_clean
= this_clean
;
4129 if (*config
->accounting_dir
)
4131 static clockt next_acct
= 0;
4132 static clockt next_shut_acct
= 0;
4134 if (next_acct
<= TIME
)
4136 // Dump accounting data
4137 next_acct
= TIME
+ ACCT_TIME
;
4138 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4141 else if (next_shut_acct
<= TIME
)
4143 // Dump accounting data for shutdown sessions
4144 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4151 // Are we the master and shutting down??
4152 if (config
->cluster_iam_master
)
4153 cluster_heartbeat(); // Flush any queued changes..
4155 // Ok. Notify everyone we're shutting down. If we're
4156 // the master, this will force an election.
4157 cluster_send_ping(0);
4160 // Important!!! We MUST not process any packets past this point!
4161 LOG(1, 0, 0, "Shutdown complete\n");
4164 static void stripdomain(char *host
)
4168 if ((p
= strchr(host
, '.')))
4174 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4180 while (fgets(buf
, sizeof(buf
), resolv
))
4182 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4185 if (!isspace(buf
[6]))
4189 while (isspace(*b
)) b
++;
4194 while (*b
&& !isspace(*b
)) b
++;
4196 if (buf
[0] == 'd') // domain is canonical
4202 // first search line
4205 // hold, may be subsequent domain line
4206 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4217 int hl
= strlen(host
);
4218 int dl
= strlen(domain
);
4219 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4220 host
[hl
-dl
- 1] = 0;
4224 *p
= 0; // everything after first dot
4229 // Init data structures
4230 static void initdata(int optdebug
, char *optconfig
)
4234 if (!(config
= shared_malloc(sizeof(configt
))))
4236 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4240 memset(config
, 0, sizeof(configt
));
4241 time(&config
->start_time
);
4242 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4243 config
->debug
= optdebug
;
4244 config
->num_tbfs
= MAXTBFS
;
4245 config
->rl_rate
= 28; // 28kbps
4246 config
->cluster_mcast_ttl
= 1;
4247 config
->cluster_master_min_adv
= 1;
4248 config
->ppp_restart_time
= 3;
4249 config
->ppp_max_configure
= 10;
4250 config
->ppp_max_failure
= 5;
4251 config
->kill_timedout_sessions
= 1;
4252 strcpy(config
->random_device
, RANDOMDEVICE
);
4254 log_stream
= stderr
;
4257 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4259 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4262 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4265 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4267 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4270 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4272 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4275 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4277 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4280 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4282 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4285 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4287 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4291 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4293 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4297 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4299 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4303 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4305 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4309 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4311 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4314 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4316 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4318 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4321 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4323 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4325 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4328 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4330 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4331 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4332 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4333 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4334 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4336 // Put all the sessions on the free list marked as undefined.
4337 for (i
= 1; i
< MAXSESSION
; i
++)
4339 session
[i
].next
= i
+ 1;
4340 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4342 session
[MAXSESSION
- 1].next
= 0;
4345 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4346 for (i
= 1; i
< MAXTUNNEL
; i
++)
4347 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4349 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4350 bundle
[i
].state
= BUNDLEUNDEF
;
4355 // Grab my hostname unless it's been specified
4356 gethostname(hostname
, sizeof(hostname
));
4357 stripdomain(hostname
);
4360 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4363 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4365 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4371 static int assign_ip_address(sessionidt s
)
4375 time_t best_time
= time_now
;
4376 char *u
= session
[s
].user
;
4380 CSTAT(assign_ip_address
);
4382 for (i
= 1; i
< ip_pool_size
; i
++)
4384 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4387 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4394 if (ip_address_pool
[i
].last
< best_time
)
4397 if (!(best_time
= ip_address_pool
[i
].last
))
4398 break; // never used, grab this one
4404 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4408 session
[s
].ip
= ip_address_pool
[best
].address
;
4409 session
[s
].ip_pool_index
= best
;
4410 ip_address_pool
[best
].assigned
= 1;
4411 ip_address_pool
[best
].last
= time_now
;
4412 ip_address_pool
[best
].session
= s
;
4413 if (session
[s
].walled_garden
)
4414 /* Don't track addresses of users in walled garden (note: this
4415 means that their address isn't "sticky" even if they get
4417 ip_address_pool
[best
].user
[0] = 0;
4419 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4422 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4423 reuse
? "Reusing" : "Allocating", best
);
4428 static void free_ip_address(sessionidt s
)
4430 int i
= session
[s
].ip_pool_index
;
4433 CSTAT(free_ip_address
);
4436 return; // what the?
4438 if (i
< 0) // Is this actually part of the ip pool?
4442 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4444 ip_address_pool
[i
].assigned
= 0;
4445 ip_address_pool
[i
].session
= 0;
4446 ip_address_pool
[i
].last
= time_now
;
4450 // Fsck the address pool against the session table.
4451 // Normally only called when we become a master.
4453 // This isn't perfect: We aren't keep tracking of which
4454 // users used to have an IP address.
4456 void rebuild_address_pool(void)
4461 // Zero the IP pool allocation, and build
4462 // a map from IP address to pool index.
4463 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4465 ip_address_pool
[i
].assigned
= 0;
4466 ip_address_pool
[i
].session
= 0;
4467 if (!ip_address_pool
[i
].address
)
4470 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4473 for (i
= 0; i
< MAXSESSION
; ++i
)
4476 if (!(session
[i
].opened
&& session
[i
].ip
))
4479 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4481 if (session
[i
].ip_pool_index
< 0)
4483 // Not allocated out of the pool.
4484 if (ipid
< 1) // Not found in the pool either? good.
4487 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4488 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4490 // Fall through and process it as part of the pool.
4494 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4496 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4498 session
[i
].ip_pool_index
= ipid
;
4502 ip_address_pool
[ipid
].assigned
= 1;
4503 ip_address_pool
[ipid
].session
= i
;
4504 ip_address_pool
[ipid
].last
= time_now
;
4505 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4506 session
[i
].ip_pool_index
= ipid
;
4507 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4512 // Fix the address pool to match a changed session.
4513 // (usually when the master sends us an update).
4514 static void fix_address_pool(int sid
)
4518 ipid
= session
[sid
].ip_pool_index
;
4520 if (ipid
> ip_pool_size
)
4521 return; // Ignore it. rebuild_address_pool will fix it up.
4523 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4524 return; // Just ignore it. rebuild_address_pool will take care of it.
4526 ip_address_pool
[ipid
].assigned
= 1;
4527 ip_address_pool
[ipid
].session
= sid
;
4528 ip_address_pool
[ipid
].last
= time_now
;
4529 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4533 // Add a block of addresses to the IP pool to hand out.
4535 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4539 prefixlen
= 32; // Host route only.
4541 addr
&= 0xffffffff << (32 - prefixlen
);
4543 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4546 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4548 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4549 continue; // Skip 0 and broadcast addresses.
4551 ip_address_pool
[ip_pool_size
].address
= i
;
4552 ip_address_pool
[ip_pool_size
].assigned
= 0;
4554 if (ip_pool_size
>= MAXIPPOOL
)
4556 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4562 // Initialize the IP address pool
4563 static void initippool()
4568 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4570 if (!(f
= fopen(IPPOOLFILE
, "r")))
4572 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4576 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4579 buf
[4095] = 0; // Force it to be zero terminated/
4581 if (*buf
== '#' || *buf
== '\n')
4582 continue; // Skip comments / blank lines
4583 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4584 if ((p
= (char *)strchr(buf
, ':')))
4588 src
= inet_addr(buf
);
4589 if (src
== INADDR_NONE
)
4591 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4594 // This entry is for a specific IP only
4595 if (src
!= config
->bind_address
)
4600 if ((p
= (char *)strchr(pool
, '/')))
4604 in_addr_t start
= 0;
4606 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4608 if (!*p
|| !(numbits
= atoi(p
)))
4610 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4613 start
= ntohl(inet_addr(pool
));
4615 // Add a static route for this pool
4616 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4617 fmtaddr(htonl(start
), 0), numbits
);
4619 routeset(0, start
, numbits
, 0, 1);
4621 add_to_ip_pool(start
, numbits
);
4625 // It's a single ip address
4626 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4630 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4633 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4635 struct sockaddr_in snoop_addr
= {0};
4636 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4639 snoop_addr
.sin_family
= AF_INET
;
4640 snoop_addr
.sin_addr
.s_addr
= destination
;
4641 snoop_addr
.sin_port
= ntohs(port
);
4643 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4644 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4645 htons(snoop_addr
.sin_port
));
4647 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4648 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4650 STAT(packets_snooped
);
4653 static int dump_session(FILE **f
, sessiont
*s
)
4655 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4660 char filename
[1024];
4662 time_t now
= time(NULL
);
4664 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4665 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4667 if (!(*f
= fopen(filename
, "w")))
4669 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4673 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4674 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4679 "# format: username ip qos uptxoctets downrxoctets\n",
4681 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4686 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4687 fprintf(*f
, "%s %s %d %u %u\n",
4688 s
->user
, // username
4689 fmtaddr(htonl(s
->ip
), 0), // ip
4690 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4691 (uint32_t) s
->cin_delta
, // uptxoctets
4692 (uint32_t) s
->cout_delta
); // downrxoctets
4694 s
->cin_delta
= s
->cout_delta
= 0;
4699 static void dump_acct_info(int all
)
4705 CSTAT(dump_acct_info
);
4709 for (i
= 0; i
< shut_acct_n
; i
++)
4710 dump_session(&f
, &shut_acct
[i
]);
4716 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4717 dump_session(&f
, &session
[i
]);
4724 int main(int argc
, char *argv
[])
4728 char *optconfig
= CONFIGFILE
;
4730 time(&basetime
); // start clock
4733 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4738 if (fork()) exit(0);
4740 freopen("/dev/null", "r", stdin
);
4741 freopen("/dev/null", "w", stdout
);
4742 freopen("/dev/null", "w", stderr
);
4751 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4754 printf("Args are:\n"
4755 "\t-d\t\tDetach from terminal\n"
4756 "\t-c <file>\tConfig file\n"
4757 "\t-h <hostname>\tForce hostname\n"
4765 // Start the timer routine off
4767 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4770 initdata(optdebug
, optconfig
);
4774 /* set hostname /after/ having read the config file */
4775 if (*config
->hostname
)
4776 strcpy(hostname
, config
->hostname
);
4777 cli_init_complete(hostname
);
4779 init_tbf(config
->num_tbfs
);
4781 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4782 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4783 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4786 rlim
.rlim_cur
= RLIM_INFINITY
;
4787 rlim
.rlim_max
= RLIM_INFINITY
;
4788 // Remove the maximum core size
4789 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4790 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4792 // Make core dumps go to /tmp
4796 if (config
->scheduler_fifo
)
4799 struct sched_param params
= {0};
4800 params
.sched_priority
= 1;
4802 if (get_nprocs() < 2)
4804 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4805 config
->scheduler_fifo
= 0;
4809 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4811 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4815 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4816 config
->scheduler_fifo
= 0;
4823 /* Set up the cluster communications port. */
4824 if (cluster_init() < 0)
4828 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4836 unsigned seed
= time_now
^ getpid();
4837 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4841 signal(SIGHUP
, sighup_handler
);
4842 signal(SIGCHLD
, sigchild_handler
);
4843 signal(SIGTERM
, shutdown_handler
);
4844 signal(SIGINT
, shutdown_handler
);
4845 signal(SIGQUIT
, shutdown_handler
);
4847 // Prevent us from getting paged out
4848 if (config
->lock_pages
)
4850 if (!mlockall(MCL_CURRENT
))
4851 LOG(1, 0, 0, "Locking pages into memory\n");
4853 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4858 /* remove plugins (so cleanup code gets run) */
4861 // Remove the PID file if we wrote it
4862 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4863 unlink(config
->pid_file
);
4865 /* kill CLI children */
4866 signal(SIGTERM
, SIG_IGN
);
4871 static void sighup_handler(int sig
)
4876 static void shutdown_handler(int sig
)
4878 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4881 static void sigchild_handler(int sig
)
4883 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4887 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4890 *challenge_response
= NULL
;
4892 if (!*config
->l2tp_secret
)
4894 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4898 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4900 *challenge_response
= calloc(17, 1);
4903 MD5_Update(&ctx
, &id
, 1);
4904 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4905 MD5_Update(&ctx
, challenge
, challenge_length
);
4906 MD5_Final(*challenge_response
, &ctx
);
4911 static int facility_value(char *name
)
4914 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4916 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4917 return facilitynames
[i
].c_val
;
4922 static void update_config()
4926 static int timeout
= 0;
4927 static int interval
= 0;
4934 if (log_stream
!= stderr
)
4940 if (*config
->log_filename
)
4942 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4944 char *p
= config
->log_filename
+ 7;
4947 openlog("l2tpns", LOG_PID
, facility_value(p
));
4951 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4953 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4955 fseek(log_stream
, 0, SEEK_END
);
4956 setbuf(log_stream
, NULL
);
4960 log_stream
= stderr
;
4961 setbuf(log_stream
, NULL
);
4967 log_stream
= stderr
;
4968 setbuf(log_stream
, NULL
);
4971 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4972 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4974 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4975 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4976 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4978 // reset MRU/MSS globals
4979 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4980 if (MRU
> PPPoE_MRU
)
4983 MSS
= MRU
- TCP_HDRS
;
4986 config
->numradiusservers
= 0;
4987 for (i
= 0; i
< MAXRADSERVER
; i
++)
4988 if (config
->radiusserver
[i
])
4990 config
->numradiusservers
++;
4991 // Set radius port: if not set, take the port from the
4992 // first radius server. For the first radius server,
4993 // take the #defined default value from l2tpns.h
4995 // test twice, In case someone works with
4996 // a secondary radius server without defining
4997 // a primary one, this will work even then.
4998 if (i
> 0 && !config
->radiusport
[i
])
4999 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5000 if (!config
->radiusport
[i
])
5001 config
->radiusport
[i
] = RADPORT
;
5004 if (!config
->numradiusservers
)
5005 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5007 // parse radius_authtypes_s
5008 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5009 p
= config
->radius_authtypes_s
;
5012 char *s
= strpbrk(p
, " \t,");
5018 while (*s
== ' ' || *s
== '\t')
5025 if (!strncasecmp("chap", p
, strlen(p
)))
5027 else if (!strncasecmp("pap", p
, strlen(p
)))
5030 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5032 config
->radius_authtypes
|= type
;
5033 if (!config
->radius_authprefer
)
5034 config
->radius_authprefer
= type
;
5039 if (!config
->radius_authtypes
)
5041 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5042 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5045 // normalise radius_authtypes_s
5046 if (config
->radius_authprefer
== AUTHPAP
)
5048 strcpy(config
->radius_authtypes_s
, "pap");
5049 if (config
->radius_authtypes
& AUTHCHAP
)
5050 strcat(config
->radius_authtypes_s
, ", chap");
5054 strcpy(config
->radius_authtypes_s
, "chap");
5055 if (config
->radius_authtypes
& AUTHPAP
)
5056 strcat(config
->radius_authtypes_s
, ", pap");
5059 if (!config
->radius_dae_port
)
5060 config
->radius_dae_port
= DAEPORT
;
5062 // re-initialise the random number source
5063 initrandom(config
->random_device
);
5066 for (i
= 0; i
< MAXPLUGINS
; i
++)
5068 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5071 if (*config
->plugins
[i
])
5074 add_plugin(config
->plugins
[i
]);
5076 else if (*config
->old_plugins
[i
])
5079 remove_plugin(config
->old_plugins
[i
]);
5084 guest_accounts_num
= 0;
5085 char *p2
= config
->guest_user
;
5088 char *s
= strpbrk(p2
, " \t,");
5092 while (*s
== ' ' || *s
== '\t')
5099 strcpy(guest_users
[guest_accounts_num
], p2
);
5100 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5101 guest_accounts_num
++;
5104 // Rebuild the guest_user array
5105 strcpy(config
->guest_user
, "");
5107 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5109 strcat(config
->guest_user
, guest_users
[ui
]);
5110 if (ui
<guest_accounts_num
-1)
5112 strcat(config
->guest_user
, ",");
5117 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5118 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5119 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5120 if (!*config
->cluster_interface
)
5121 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5123 if (!config
->cluster_hb_interval
)
5124 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5126 if (!config
->cluster_hb_timeout
)
5127 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5129 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5131 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5132 // late, ensure we're sufficiently larger than that
5133 int t
= 4 * config
->cluster_hb_interval
+ 11;
5135 if (config
->cluster_hb_timeout
< t
)
5137 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5138 config
->cluster_hb_timeout
= t
;
5141 // Push timing changes to the slaves immediately if we're the master
5142 if (config
->cluster_iam_master
)
5143 cluster_heartbeat();
5145 interval
= config
->cluster_hb_interval
;
5146 timeout
= config
->cluster_hb_timeout
;
5150 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5153 if ((f
= fopen(config
->pid_file
, "w")))
5155 fprintf(f
, "%d\n", getpid());
5157 config
->wrote_pid
= 1;
5161 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5166 static void read_config_file()
5170 if (!config
->config_file
) return;
5171 if (!(f
= fopen(config
->config_file
, "r")))
5173 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5177 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5179 LOG(3, 0, 0, "Done reading config file\n");
5183 int sessionsetup(sessionidt s
, tunnelidt t
)
5185 // A session now exists, set it up
5191 CSTAT(sessionsetup
);
5193 LOG(3, s
, t
, "Doing session setup for session\n");
5195 // Join a bundle if the MRRU option is accepted
5196 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5198 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5199 if (join_bundle(s
) > 0)
5200 cluster_send_bundle(session
[s
].bundle
);
5203 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5204 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5211 assign_ip_address(s
);
5214 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5215 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5218 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5219 fmtaddr(htonl(session
[s
].ip
), 0));
5223 // Make sure this is right
5224 session
[s
].tunnel
= t
;
5226 // zap old sessions with same IP and/or username
5227 // Don't kill gardened sessions - doing so leads to a DoS
5228 // from someone who doesn't need to know the password
5231 user
= session
[s
].user
;
5232 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5234 if (i
== s
) continue;
5235 if (!session
[s
].opened
) continue;
5236 // Allow duplicate sessions for multilink ones of the same bundle.
5237 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5239 if (ip
== session
[i
].ip
)
5241 sessionkill(i
, "Duplicate IP address");
5245 if (config
->allow_duplicate_users
) continue;
5246 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5250 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5252 if (!strcasecmp(user
, guest_users
[gu
]))
5258 if (found
) continue;
5260 // Drop the new session in case of duplicate sessionss, not the old one.
5261 if (!strcasecmp(user
, session
[i
].user
))
5262 sessionkill(i
, "Duplicate session for users");
5266 // no need to set a route for the same IP address of the bundle
5267 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5271 // Add the route for this session.
5272 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5274 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5275 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5278 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5281 // Static IPs need to be routed if not already
5282 // convered by a Framed-Route. Anything else is part
5283 // of the IP address pool and is already routed, it
5284 // just needs to be added to the IP cache.
5285 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5286 if (session
[s
].ip_pool_index
== -1) // static ip
5288 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5291 cache_ipmap(session
[s
].ip
, s
);
5294 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5295 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5297 // Run the plugin's against this new session.
5299 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5300 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5303 // Allocate TBFs if throttled
5304 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5305 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5307 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5309 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5310 fmtaddr(htonl(session
[s
].ip
), 0),
5311 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5313 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5315 return 1; // RADIUS OK and IP allocated, done...
5319 // This session just got dropped on us by the master or something.
5320 // Make sure our tables up up to date...
5322 int load_session(sessionidt s
, sessiont
*new)
5328 if (new->ip_pool_index
>= MAXIPPOOL
||
5329 new->tunnel
>= MAXTUNNEL
)
5331 LOG(0, s
, 0, "Strange session update received!\n");
5332 // FIXME! What to do here?
5337 // Ok. All sanity checks passed. Now we're committed to
5338 // loading the new session.
5341 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5343 // See if routes/ip cache need updating
5344 if (new->ip
!= session
[s
].ip
)
5347 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5348 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5349 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5357 // remove old routes...
5358 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5360 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5361 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5364 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5370 if (session
[s
].ip_pool_index
== -1) // static IP
5372 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5374 else // It's part of the IP pool, remove it manually.
5375 uncache_ipmap(session
[s
].ip
);
5380 // add new routes...
5381 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5383 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5384 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5387 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5393 // If there's a new one, add it.
5394 if (new->ip_pool_index
== -1)
5396 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5399 cache_ipmap(new->ip
, s
);
5404 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5405 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5408 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5410 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5414 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5416 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5417 new->filter_out
= 0;
5420 if (new->filter_in
!= session
[s
].filter_in
)
5422 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5423 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5426 if (new->filter_out
!= session
[s
].filter_out
)
5428 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5429 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5432 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5433 // for walking the sessions to forward byte counts to the master.
5434 config
->cluster_highest_sessionid
= s
;
5436 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5438 // Do fixups into address pool.
5439 if (new->ip_pool_index
!= -1)
5440 fix_address_pool(s
);
5445 static void initplugins()
5449 loaded_plugins
= ll_init();
5450 // Initialize the plugins to nothing
5451 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5452 plugins
[i
] = ll_init();
5455 static void *open_plugin(char *plugin_name
, int load
)
5457 char path
[256] = "";
5459 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5460 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5461 return dlopen(path
, RTLD_NOW
);
5464 // plugin callback to get a config value
5465 static void *getconfig(char *key
, enum config_typet type
)
5469 for (i
= 0; config_values
[i
].key
; i
++)
5471 if (!strcmp(config_values
[i
].key
, key
))
5473 if (config_values
[i
].type
== type
)
5474 return ((void *) config
) + config_values
[i
].offset
;
5476 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5477 key
, type
, config_values
[i
].type
);
5483 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5487 static int add_plugin(char *plugin_name
)
5489 static struct pluginfuncs funcs
= {
5494 sessiontbysessionidt
,
5495 sessionidtbysessiont
,
5502 cluster_send_session
,
5505 void *p
= open_plugin(plugin_name
, 1);
5506 int (*initfunc
)(struct pluginfuncs
*);
5511 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5515 if (ll_contains(loaded_plugins
, p
))
5518 return 0; // already loaded
5522 int *v
= dlsym(p
, "plugin_api_version");
5523 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5525 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5531 if ((initfunc
= dlsym(p
, "plugin_init")))
5533 if (!initfunc(&funcs
))
5535 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5541 ll_push(loaded_plugins
, p
);
5543 for (i
= 0; i
< max_plugin_functions
; i
++)
5546 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5548 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5549 ll_push(plugins
[i
], x
);
5553 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5557 static void run_plugin_done(void *plugin
)
5559 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5565 static int remove_plugin(char *plugin_name
)
5567 void *p
= open_plugin(plugin_name
, 0);
5573 if (ll_contains(loaded_plugins
, p
))
5576 for (i
= 0; i
< max_plugin_functions
; i
++)
5579 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5580 ll_delete(plugins
[i
], x
);
5583 ll_delete(loaded_plugins
, p
);
5589 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5593 int run_plugins(int plugin_type
, void *data
)
5595 int (*func
)(void *data
);
5597 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5598 return PLUGIN_RET_ERROR
;
5600 ll_reset(plugins
[plugin_type
]);
5601 while ((func
= ll_next(plugins
[plugin_type
])))
5605 if (r
!= PLUGIN_RET_OK
)
5606 return r
; // stop here
5609 return PLUGIN_RET_OK
;
5612 static void plugins_done()
5616 ll_reset(loaded_plugins
);
5617 while ((p
= ll_next(loaded_plugins
)))
5621 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5623 struct nsctl request
;
5624 struct nsctl response
;
5625 int type
= unpack_control(&request
, buf
, len
);
5629 if (log_stream
&& config
->debug
>= 4)
5633 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5634 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5638 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5639 dump_control(&request
, log_stream
);
5645 case NSCTL_REQ_LOAD
:
5646 if (request
.argc
!= 1)
5648 response
.type
= NSCTL_RES_ERR
;
5650 response
.argv
[0] = "name of plugin required";
5652 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5654 response
.type
= NSCTL_RES_ERR
;
5656 response
.argv
[0] = !r
5657 ? "plugin already loaded"
5658 : "error loading plugin";
5662 response
.type
= NSCTL_RES_OK
;
5668 case NSCTL_REQ_UNLOAD
:
5669 if (request
.argc
!= 1)
5671 response
.type
= NSCTL_RES_ERR
;
5673 response
.argv
[0] = "name of plugin required";
5675 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5677 response
.type
= NSCTL_RES_ERR
;
5679 response
.argv
[0] = !r
5680 ? "plugin not loaded"
5681 : "plugin not found";
5685 response
.type
= NSCTL_RES_OK
;
5691 case NSCTL_REQ_HELP
:
5692 response
.type
= NSCTL_RES_OK
;
5695 ll_reset(loaded_plugins
);
5696 while ((p
= ll_next(loaded_plugins
)))
5698 char **help
= dlsym(p
, "plugin_control_help");
5699 while (response
.argc
< 0xff && help
&& *help
)
5700 response
.argv
[response
.argc
++] = *help
++;
5705 case NSCTL_REQ_CONTROL
:
5707 struct param_control param
= {
5708 config
->cluster_iam_master
,
5715 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5717 if (r
== PLUGIN_RET_ERROR
)
5719 response
.type
= NSCTL_RES_ERR
;
5721 response
.argv
[0] = param
.additional
5723 : "error returned by plugin";
5725 else if (r
== PLUGIN_RET_NOTMASTER
)
5727 static char msg
[] = "must be run on master: 000.000.000.000";
5729 response
.type
= NSCTL_RES_ERR
;
5731 if (config
->cluster_master_address
)
5733 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5734 response
.argv
[0] = msg
;
5738 response
.argv
[0] = "must be run on master: none elected";
5741 else if (!(param
.response
& NSCTL_RESPONSE
))
5743 response
.type
= NSCTL_RES_ERR
;
5745 response
.argv
[0] = param
.response
5746 ? "unrecognised response value from plugin"
5747 : "unhandled action";
5751 response
.type
= param
.response
;
5753 if (param
.additional
)
5756 response
.argv
[0] = param
.additional
;
5764 response
.type
= NSCTL_RES_ERR
;
5766 response
.argv
[0] = "error unpacking control packet";
5769 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5772 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5776 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5779 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5780 if (log_stream
&& config
->debug
>= 4)
5782 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5783 dump_control(&response
, log_stream
);
5787 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5788 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5793 static tunnelidt
new_tunnel()
5796 for (i
= 1; i
< MAXTUNNEL
; i
++)
5798 if (tunnel
[i
].state
== TUNNELFREE
)
5800 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5801 if (i
> config
->cluster_highest_tunnelid
)
5802 config
->cluster_highest_tunnelid
= i
;
5806 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5811 // We're becoming the master. Do any required setup..
5813 // This is principally telling all the plugins that we're
5814 // now a master, and telling them about all the sessions
5815 // that are active too..
5817 void become_master(void)
5820 static struct event_data d
[RADIUS_FDS
];
5821 struct epoll_event e
;
5823 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5825 // running a bunch of iptables commands is slow and can cause
5826 // the master to drop tunnels on takeover--kludge around the
5827 // problem by forking for the moment (note: race)
5828 if (!fork_and_close())
5830 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5832 if (!session
[s
].opened
) // Not an in-use session.
5835 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5842 for (i
= 0; i
< RADIUS_FDS
; i
++)
5844 d
[i
].type
= FD_TYPE_RADIUS
;
5848 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5852 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5858 if (CLI_HELP_REQUESTED
)
5859 return CLI_HELP_NO_ARGS
;
5862 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5864 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5867 if (!session
[s
].opened
)
5870 idle
= time_now
- session
[s
].last_data
;
5871 idle
/= 5 ; // In multiples of 5 seconds.
5881 for (i
= 0; i
< 63; ++i
)
5883 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5885 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5886 cli_print(cli
, "%d total sessions open.", count
);
5890 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5896 if (CLI_HELP_REQUESTED
)
5897 return CLI_HELP_NO_ARGS
;
5900 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5902 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5905 if (!session
[s
].opened
)
5908 d
= time_now
- session
[s
].opened
;
5911 while (d
> 1 && open
< 32)
5921 for (i
= 0; i
< 30; ++i
)
5923 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5926 cli_print(cli
, "%d total sessions open.", count
);
5932 * This unencodes the AVP using the L2TP secret and the previously
5933 * stored random vector. It overwrites the hidden data with the
5934 * unhidden AVP subformat.
5936 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5942 uint16_t m
= htons(type
);
5944 // Compute initial pad
5946 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5947 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5948 MD5_Update(&ctx
, vector
, vec_len
);
5949 MD5_Final(digest
, &ctx
);
5951 // pointer to last decoded 16 octets
5956 // calculate a new pad based on the last decoded block
5957 if (d
>= sizeof(digest
))
5960 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5961 MD5_Update(&ctx
, last
, sizeof(digest
));
5962 MD5_Final(digest
, &ctx
);
5968 *value
++ ^= digest
[d
++];
5973 int find_filter(char const *name
, size_t len
)
5978 for (i
= 0; i
< MAXFILTER
; i
++)
5980 if (!*ip_filters
[i
].name
)
5988 if (strlen(ip_filters
[i
].name
) != len
)
5991 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5998 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6002 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6003 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6004 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6005 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6006 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6012 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6016 case FILTER_FLAG_OP_ANY
:
6017 return (flags
& sflags
) || (~flags
& cflags
);
6019 case FILTER_FLAG_OP_ALL
:
6020 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6022 case FILTER_FLAG_OP_EST
:
6023 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6029 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6031 uint16_t frag_offset
;
6035 uint16_t src_port
= 0;
6036 uint16_t dst_port
= 0;
6038 ip_filter_rulet
*rule
;
6040 if (len
< 20) // up to end of destination address
6043 if ((*buf
>> 4) != 4) // IPv4
6046 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6048 src_ip
= *(in_addr_t
*) (buf
+ 12);
6049 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6051 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6053 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6054 if (len
< l
+ 4) // ports
6057 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6058 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6059 if (proto
== IPPROTO_TCP
)
6061 if (len
< l
+ 14) // flags
6064 flags
= buf
[l
+ 13] & 0x3f;
6068 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6070 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6073 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6074 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6077 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6078 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6083 // layer 4 deny rules are skipped
6084 if (rule
->action
== FILTER_ACTION_DENY
&&
6085 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6093 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6095 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6098 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6101 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6102 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6109 return rule
->action
== FILTER_ACTION_PERMIT
;