3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
7 char const *cvs_id_l2tpns
= "$Id: l2tpns.c,v 1.176 2011/01/20 12:48:40 bodea Exp $";
13 #include <linux/if_tun.h>
17 #include <net/route.h>
20 #include <netinet/in.h>
21 #include <netinet/ip6.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
31 #include <sys/resource.h>
39 #include <sys/sysinfo.h>
41 #include <linux/netlink.h>
42 #include <linux/rtnetlink.h>
49 #include "constants.h"
59 configt
*config
= NULL
; // all configuration
60 int nlfd
= -1; // netlink socket
61 int tunfd
= -1; // tun interface file handle. (network device)
62 int udpfd
= -1; // UDP file handle
63 int controlfd
= -1; // Control signal handle
64 int clifd
= -1; // Socket listening for CLI connections.
65 int daefd
= -1; // Socket listening for DAE connections.
66 int snoopfd
= -1; // UDP file handle for sending out intercept data
67 int *radfds
= NULL
; // RADIUS requests file handles
68 int rand_fd
= -1; // Random data source
69 int cluster_sockfd
= -1; // Intra-cluster communications socket.
70 int epollfd
= -1; // event polling
71 time_t basetime
= 0; // base clock
72 char hostname
[1000] = ""; // us.
73 static int tunidx
; // ifr_ifindex of tun device
74 int nlseqnum
= 0; // netlink sequence number
75 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
76 static int syslog_log
= 0; // are we logging to syslog
77 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
78 uint32_t last_id
= 0; // Unique ID for radius accounting
80 char guest_users
[10][32]; // Array of guest users
81 int guest_accounts_num
= 0; // Number of guest users
83 // calculated from config->l2tp_mtu
84 uint16_t MRU
= 0; // PPP MRU
85 uint16_t MSS
= 0; // TCP MSS
87 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
88 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
93 } ip_hash
[256]; // Mapping from IP address to session structures.
97 struct ipv6radix
*branch
;
98 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
101 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
102 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
105 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
106 time_t time_now
= 0; // Current time in seconds since epoch.
107 static char time_now_string
[64] = {0}; // Current time as a string.
108 static int time_changed
= 0; // time_now changed
109 char main_quit
= 0; // True if we're in the process of exiting.
110 static char main_reload
= 0; // Re-load pending
111 linked_list
*loaded_plugins
;
112 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
114 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
115 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
117 config_descriptt config_values
[] = {
118 CONFIG("debug", debug
, INT
),
119 CONFIG("log_file", log_filename
, STRING
),
120 CONFIG("pid_file", pid_file
, STRING
),
121 CONFIG("random_device", random_device
, STRING
),
122 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
123 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
124 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
125 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
126 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
127 CONFIG("primary_dns", default_dns1
, IPv4
),
128 CONFIG("secondary_dns", default_dns2
, IPv4
),
129 CONFIG("primary_radius", radiusserver
[0], IPv4
),
130 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
131 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
132 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
133 CONFIG("radius_accounting", radius_accounting
, BOOL
),
134 CONFIG("radius_interim", radius_interim
, INT
),
135 CONFIG("radius_secret", radiussecret
, STRING
),
136 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
137 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
138 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
139 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
140 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
141 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
142 CONFIG("guest_account", guest_user
, STRING
),
143 CONFIG("bind_address", bind_address
, IPv4
),
144 CONFIG("peer_address", peer_address
, IPv4
),
145 CONFIG("send_garp", send_garp
, BOOL
),
146 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
147 CONFIG("throttle_buckets", num_tbfs
, INT
),
148 CONFIG("accounting_dir", accounting_dir
, STRING
),
149 CONFIG("dump_speed", dump_speed
, BOOL
),
150 CONFIG("multi_read_count", multi_read_count
, INT
),
151 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
152 CONFIG("lock_pages", lock_pages
, BOOL
),
153 CONFIG("icmp_rate", icmp_rate
, INT
),
154 CONFIG("packet_limit", max_packets
, INT
),
155 CONFIG("cluster_address", cluster_address
, IPv4
),
156 CONFIG("cluster_interface", cluster_interface
, STRING
),
157 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
158 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
159 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
160 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
161 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
165 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
;
447 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
448 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
450 req
.rt
.rtm_family
= AF_INET
;
451 req
.rt
.rtm_dst_len
= prefixlen
;
452 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
453 req
.rt
.rtm_protocol
= RTPROT_BOOT
; // XXX
454 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
455 req
.rt
.rtm_type
= RTN_UNICAST
;
457 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
459 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
463 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
466 LOG(1, s
, 0, "Route %s %s/%d%s%s\n", add
? "add" : "del",
467 fmtaddr(htonl(ip
), 0), prefixlen
,
468 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
470 if (netlink_send(&req
.nh
) < 0)
471 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
475 bgp_add_route(htonl(ip
), prefixlen
);
477 bgp_del_route(htonl(ip
), prefixlen
);
480 // Add/Remove the IPs to the 'sessionbyip' cache.
481 // Note that we add the zero address in the case of
482 // a network route. Roll on CIDR.
484 // Note that 's == 0' implies this is the address pool.
485 // We still cache it here, because it will pre-fill
486 // the malloc'ed tree.
490 if (!add
) // Are we deleting a route?
491 s
= 0; // Caching the session as '0' is the same as uncaching.
493 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
498 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
506 char ipv6addr
[INET6_ADDRSTRLEN
];
508 if (!config
->ipv6_prefix
.s6_addr
[0])
510 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
514 memset(&req
, 0, sizeof(req
));
518 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
519 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
522 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
523 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
525 req
.rt
.rtm_family
= AF_INET6
;
526 req
.rt
.rtm_dst_len
= prefixlen
;
527 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
528 req
.rt
.rtm_protocol
= RTPROT_BOOT
; // XXX
529 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
530 req
.rt
.rtm_type
= RTN_UNICAST
;
532 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
533 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
535 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
537 LOG(1, 0, 0, "Route %s %s/%d\n",
539 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
542 if (netlink_send(&req
.nh
) < 0)
543 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
545 // FIXME: need to add BGP routing (RFC2858)
549 if (!add
) // Are we deleting a route?
550 s
= 0; // Caching the session as '0' is the same as uncaching.
552 cache_ipv6map(ip
, prefixlen
, s
);
559 // Set up netlink socket
560 static void initnetlink(void)
562 struct sockaddr_nl nladdr
;
564 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
567 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
571 memset(&nladdr
, 0, sizeof(nladdr
));
572 nladdr
.nl_family
= AF_NETLINK
;
573 nladdr
.nl_pid
= getpid();
575 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
577 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
582 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
584 struct sockaddr_nl nladdr
;
588 nh
->nlmsg_pid
= getpid();
589 nh
->nlmsg_seq
= ++nlseqnum
;
591 // set kernel address
592 memset(&nladdr
, 0, sizeof(nladdr
));
593 nladdr
.nl_family
= AF_NETLINK
;
595 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
596 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
598 return sendmsg(nlfd
, &msg
, 0);
601 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
603 struct sockaddr_nl nladdr
;
607 // set kernel address
608 memset(&nladdr
, 0, sizeof(nladdr
));
609 nladdr
.nl_family
= AF_NETLINK
;
611 iov
= (struct iovec
){ buf
, len
};
612 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
614 return recvmsg(nlfd
, &msg
, 0);
617 /* adapted from iproute2 */
618 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
620 int len
= RTA_LENGTH(alen
);
623 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
624 rta
->rta_type
= type
;
626 memcpy(RTA_DATA(rta
), data
, alen
);
627 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
630 // messages corresponding to different phases seq number
631 static char *tun_nl_phase_msg
[] = {
633 "getting tun interface index",
634 "setting tun interface parameters",
635 "setting tun IPv4 address",
636 "setting tun LL IPv6 address",
637 "setting tun global IPv6 address",
641 // Set up TUN interface
642 static void inittun(void)
646 memset(&ifr
, 0, sizeof(ifr
));
647 ifr
.ifr_flags
= IFF_TUN
;
649 tunfd
= open(TUNDEVICE
, O_RDWR
);
652 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
656 int flags
= fcntl(tunfd
, F_GETFL
, 0);
657 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
659 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
661 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
664 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
) - 1);
665 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
));
667 tunidx
= if_nametoindex(config
->tundevice
);
670 LOG(0, 0, 0, "Can't get tun interface index\n");
679 struct ifinfomsg ifinfo
;
680 struct ifaddrmsg ifaddr
;
682 char rtdata
[32]; // 32 should be enough
684 uint32_t txqlen
, mtu
;
687 memset(&req
, 0, sizeof(req
));
689 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
690 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
691 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
693 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
694 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
695 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
696 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
698 /* Bump up the qlen to deal with bursts from the network */
700 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
701 /* set MTU to modem MRU */
703 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
705 if (netlink_send(&req
.nh
) < 0)
708 memset(&req
, 0, sizeof(req
));
710 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
711 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
712 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
714 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
715 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
716 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
717 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
719 if (config
->bind_address
)
720 ip
= config
->bind_address
;
722 ip
= 0x01010101; // 1.1.1.1
723 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
725 if (netlink_send(&req
.nh
) < 0)
728 // Only setup IPv6 on the tun device if we have a configured prefix
729 if (config
->ipv6_prefix
.s6_addr
[0]) {
732 memset(&req
, 0, sizeof(req
));
734 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
735 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
736 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
738 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
739 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
740 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
741 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
743 // Link local address is FE80::1
744 memset(&ip6
, 0, sizeof(ip6
));
745 ip6
.s6_addr
[0] = 0xFE;
746 ip6
.s6_addr
[1] = 0x80;
748 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
750 if (netlink_send(&req
.nh
) < 0)
753 memset(&req
, 0, sizeof(req
));
755 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
756 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
757 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
759 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
760 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
761 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
762 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
764 // Global address is prefix::1
765 ip6
= config
->ipv6_prefix
;
767 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
769 if (netlink_send(&req
.nh
) < 0)
773 memset(&req
, 0, sizeof(req
));
775 req
.nh
.nlmsg_type
= NLMSG_DONE
;
776 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
778 if (netlink_send(&req
.nh
) < 0)
781 // if we get an error for seqnum < min_initok_nlseqnum,
782 // we must exit as initialization went wrong
783 if (config
->ipv6_prefix
.s6_addr
[0])
784 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
786 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
792 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
797 static void initudp(void)
800 struct sockaddr_in addr
;
803 memset(&addr
, 0, sizeof(addr
));
804 addr
.sin_family
= AF_INET
;
805 addr
.sin_port
= htons(L2TPPORT
);
806 addr
.sin_addr
.s_addr
= config
->bind_address
;
807 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
808 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
810 int flags
= fcntl(udpfd
, F_GETFL
, 0);
811 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
813 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
815 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
820 memset(&addr
, 0, sizeof(addr
));
821 addr
.sin_family
= AF_INET
;
822 addr
.sin_port
= htons(NSCTL_PORT
);
823 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
824 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
825 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
826 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
828 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
832 // Dynamic Authorization Extensions to RADIUS
833 memset(&addr
, 0, sizeof(addr
));
834 addr
.sin_family
= AF_INET
;
835 addr
.sin_port
= htons(config
->radius_dae_port
);
836 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
837 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
838 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
839 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
841 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
846 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
850 // Find session by IP, < 1 for not found
852 // Confusingly enough, this 'ip' must be
853 // in _network_ order. This being the common
854 // case when looking it up from IP packet headers.
856 // We actually use this cache for two things.
857 // #1. For used IP addresses, this maps to the
858 // session ID that it's used by.
859 // #2. For un-used IP addresses, this maps to the
860 // index into the pool table that contains that
864 static sessionidt
lookup_ipmap(in_addr_t ip
)
866 uint8_t *a
= (uint8_t *) &ip
;
867 union iphash
*h
= ip_hash
;
869 if (!(h
= h
[*a
++].idx
)) return 0;
870 if (!(h
= h
[*a
++].idx
)) return 0;
871 if (!(h
= h
[*a
++].idx
)) return 0;
876 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
878 struct ipv6radix
*curnode
;
881 char ipv6addr
[INET6_ADDRSTRLEN
];
883 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
887 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
889 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
894 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
895 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
902 sessionidt
sessionbyip(in_addr_t ip
)
904 sessionidt s
= lookup_ipmap(ip
);
907 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
913 sessionidt
sessionbyipv6(struct in6_addr ip
)
916 CSTAT(sessionbyipv6
);
918 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
919 (ip
.s6_addr
[0] == 0xFE &&
920 ip
.s6_addr
[1] == 0x80 &&
921 ip
.s6_addr16
[1] == 0 &&
922 ip
.s6_addr16
[2] == 0 &&
923 ip
.s6_addr16
[3] == 0)) {
924 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
926 s
= lookup_ipv6map(ip
);
929 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
936 // Take an IP address in HOST byte order and
937 // add it to the sessionid by IP cache.
939 // (It's actually cached in network order)
941 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
943 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
944 uint8_t *a
= (uint8_t *) &nip
;
945 union iphash
*h
= ip_hash
;
948 for (i
= 0; i
< 3; i
++)
950 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
959 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
962 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
963 // else a map to an ip pool index.
966 static void uncache_ipmap(in_addr_t ip
)
968 cache_ipmap(ip
, 0); // Assign it to the NULL session.
971 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
975 struct ipv6radix
*curnode
;
976 char ipv6addr
[INET6_ADDRSTRLEN
];
978 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
980 bytes
= prefixlen
>> 3;
983 if (curnode
->branch
== NULL
)
985 if (!(curnode
->branch
= calloc(256,
986 sizeof (struct ipv6radix
))))
989 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
996 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
997 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1001 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1002 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1008 // CLI list to dump current ipcache.
1010 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1012 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1016 if (CLI_HELP_REQUESTED
)
1017 return CLI_HELP_NO_ARGS
;
1019 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1021 for (i
= 0; i
< 256; ++i
)
1027 for (j
= 0; j
< 256; ++j
)
1033 for (k
= 0; k
< 256; ++k
)
1039 for (l
= 0; l
< 256; ++l
)
1044 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1050 cli_print(cli
, "%d entries in cache", count
);
1055 // Find session by username, 0 for not found
1056 // walled garden users aren't authenticated, so the username is
1057 // reasonably useless. Ignore them to avoid incorrect actions
1059 // This is VERY inefficent. Don't call it often. :)
1061 sessionidt
sessionbyuser(char *username
)
1064 CSTAT(sessionbyuser
);
1066 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1068 if (!session
[s
].opened
)
1071 if (session
[s
].walled_garden
)
1072 continue; // Skip walled garden users.
1074 if (!strncmp(session
[s
].user
, username
, 128))
1078 return 0; // Not found.
1081 void send_garp(in_addr_t ip
)
1087 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1090 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1093 memset(&ifr
, 0, sizeof(ifr
));
1094 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1095 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1097 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1101 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1102 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1104 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1109 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1112 static sessiont
*sessiontbysessionidt(sessionidt s
)
1114 if (!s
|| s
>= MAXSESSION
) return NULL
;
1118 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1120 sessionidt val
= s
-session
;
1121 if (s
< session
|| val
>= MAXSESSION
) return 0;
1125 // actually send a control message for a specific tunnel
1126 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1128 struct sockaddr_in addr
;
1134 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1135 STAT(tunnel_tx_errors
);
1141 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1142 STAT(tunnel_tx_errors
);
1146 memset(&addr
, 0, sizeof(addr
));
1147 addr
.sin_family
= AF_INET
;
1148 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1149 addr
.sin_port
= htons(tunnel
[t
].port
);
1151 // sequence expected, if sequence in message
1152 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1154 // If this is a control message, deal with retries
1157 tunnel
[t
].last
= time_now
; // control message sent
1158 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1161 STAT(tunnel_retries
);
1162 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1166 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1168 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1169 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1170 STAT(tunnel_tx_errors
);
1174 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1175 STAT(tunnel_tx_packets
);
1176 INC_STAT(tunnel_tx_bytes
, l
);
1180 // Tiny helper function to write data to
1181 // the 'tun' device.
1183 int tun_write(uint8_t * data
, int size
)
1185 return write(tunfd
, data
, size
);
1188 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1189 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1191 int d
= (tcp
[12] >> 4) * 4;
1198 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1201 if (tcp
+ d
> buf
+ len
) // short?
1209 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1212 if (mss
+ 2 > data
) return; // short?
1216 if (*opts
== 0) return; // end of options
1217 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1220 opts
+= opts
[1]; // skip over option
1223 if (!mss
) return; // not found
1224 orig
= ntohs(*(uint16_t *) mss
);
1226 if (orig
<= MSS
) return; // mss OK
1228 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1229 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1230 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1231 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1234 *(int16_t *) mss
= htons(MSS
);
1236 // adjust checksum (see rfc1141)
1237 sum
= orig
+ (~MSS
& 0xffff);
1238 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1239 sum
= (sum
& 0xffff) + (sum
>> 16);
1240 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1243 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1247 // Skip the four extra bytes
1259 proto
= ntohs(*(uint16_t *) p
);
1267 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1268 return; // closing session, PPP not processed
1270 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1271 processipin(s
, t
, p
, l
);
1273 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1277 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1278 return; // closing session, PPP not processed
1281 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1282 processipv6in(s
, t
, p
, l
);
1284 else if (proto
== PPPIPCP
)
1286 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1287 processipcp(s
, t
, p
, l
);
1289 else if (proto
== PPPCCP
)
1291 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1292 processccp(s
, t
, p
, l
);
1296 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1300 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1302 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1303 sp
->cout_delta
+= len
;
1305 sp
->last_data
= time_now
;
1307 sess_local
[s
].cout
+= len
; // To send to master..
1308 sess_local
[s
].pout
++;
1311 // process outgoing (to tunnel) IP
1313 static void processipout(uint8_t *buf
, int len
)
1320 uint8_t *data
= buf
; // Keep a copy of the originals.
1323 uint8_t fragbuf
[MAXETHER
+ 20];
1325 CSTAT(processipout
);
1327 if (len
< MIN_IP_SIZE
)
1329 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1330 STAT(tun_rx_errors
);
1333 if (len
>= MAXETHER
)
1335 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1336 STAT(tun_rx_errors
);
1340 // Skip the tun header
1344 // Got an IP header now
1345 if (*(uint8_t *)(buf
) >> 4 != 4)
1347 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1351 ip
= *(uint32_t *)(buf
+ 16);
1352 if (!(s
= sessionbyip(ip
)))
1354 // Is this a packet for a session that doesn't exist?
1355 static int rate
= 0; // Number of ICMP packets we've sent this second.
1356 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1358 if (last
!= time_now
)
1364 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1366 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1367 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1368 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1373 t
= session
[s
].tunnel
;
1374 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1376 LOG(3, s
, t
, "Packet size more than session MRU\n");
1382 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1383 if (config
->max_packets
> 0)
1385 if (sess_local
[s
].last_packet_out
== TIME
)
1387 int max
= config
->max_packets
;
1389 // All packets for throttled sessions are handled by the
1390 // master, so further limit by using the throttle rate.
1391 // A bit of a kludge, since throttle rate is in kbps,
1392 // but should still be generous given our average DSL
1393 // packet size is 200 bytes: a limit of 28kbps equates
1394 // to around 180 packets per second.
1395 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1396 max
= sp
->throttle_out
;
1398 if (++sess_local
[s
].packets_out
> max
)
1400 sess_local
[s
].packets_dropped
++;
1406 if (sess_local
[s
].packets_dropped
)
1408 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1409 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1410 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1411 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1415 sess_local
[s
].last_packet_out
= TIME
;
1416 sess_local
[s
].packets_out
= 1;
1417 sess_local
[s
].packets_dropped
= 0;
1421 // run access-list if any
1422 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1425 // adjust MSS on SYN and SYN,ACK packets with options
1426 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1428 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1429 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1430 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1435 // Are we throttling this session?
1436 if (config
->cluster_iam_master
)
1437 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1439 master_throttle_packet(sp
->tbf_out
, data
, size
);
1443 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1445 // We are walled-gardening this
1446 master_garden_packet(s
, data
, size
);
1450 // Add on L2TP header
1453 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1455 bid
= session
[s
].bundle
;
1456 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1457 t
= session
[s
].tunnel
;
1459 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1460 if(len
> MINFRAGLEN
)
1462 // Partition the packet to "bundle[b].num_of_links" fragments
1463 bundlet
*b
= &bundle
[bid
];
1464 uint32_t num_of_links
= b
->num_of_links
;
1465 uint32_t fraglen
= len
/ num_of_links
;
1466 fraglen
= (fraglen
> session
[s
].mru
? session
[s
].mru
: fraglen
);
1467 uint32_t last_fraglen
= fraglen
+ len
% num_of_links
;
1468 last_fraglen
= (last_fraglen
> session
[s
].mru
? len
% num_of_links
: last_fraglen
);
1469 uint32_t remain
= len
;
1471 // send the first packet
1472 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1474 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1476 update_session_out_stat(s
, sp
, fraglen
);
1478 while (remain
> last_fraglen
)
1480 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1481 t
= session
[s
].tunnel
;
1483 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1484 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1486 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1487 update_session_out_stat(s
, sp
, fraglen
);
1490 // send the last fragment
1491 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1492 t
= session
[s
].tunnel
;
1494 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1495 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1497 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1498 update_session_out_stat(s
, sp
, remain
);
1499 if (remain
!= last_fraglen
)
1500 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1503 // Send it as one frame
1504 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1506 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1507 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1508 update_session_out_stat(s
, sp
, len
);
1513 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1515 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1516 update_session_out_stat(s
, sp
, len
);
1520 // Snooping this session, send it to intercept box
1521 if (sp
->snoop_ip
&& sp
->snoop_port
)
1522 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1527 // process outgoing (to tunnel) IPv6
1529 static void processipv6out(uint8_t * buf
, int len
)
1535 struct in6_addr ip6
;
1537 uint8_t *data
= buf
; // Keep a copy of the originals.
1540 uint8_t b
[MAXETHER
+ 20];
1542 CSTAT(processipv6out
);
1544 if (len
< MIN_IP_SIZE
)
1546 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1547 STAT(tunnel_tx_errors
);
1550 if (len
>= MAXETHER
)
1552 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1553 STAT(tunnel_tx_errors
);
1557 // Skip the tun header
1561 // Got an IP header now
1562 if (*(uint8_t *)(buf
) >> 4 != 6)
1564 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1568 ip6
= *(struct in6_addr
*)(buf
+24);
1569 s
= sessionbyipv6(ip6
);
1573 ip
= *(uint32_t *)(buf
+ 32);
1574 s
= sessionbyip(ip
);
1579 // Is this a packet for a session that doesn't exist?
1580 static int rate
= 0; // Number of ICMP packets we've sent this second.
1581 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1583 if (last
!= time_now
)
1589 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1591 // FIXME: Should send icmp6 host unreachable
1595 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1597 bundleidt bid
= session
[s
].bundle
;
1598 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1599 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1601 t
= session
[s
].tunnel
;
1603 sp
->last_data
= time_now
;
1605 // FIXME: add DoS prevention/filters?
1609 // Are we throttling this session?
1610 if (config
->cluster_iam_master
)
1611 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1613 master_throttle_packet(sp
->tbf_out
, data
, size
);
1616 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1618 // We are walled-gardening this
1619 master_garden_packet(s
, data
, size
);
1623 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1625 // Add on L2TP header
1627 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1629 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1632 // Snooping this session, send it to intercept box
1633 if (sp
->snoop_ip
&& sp
->snoop_port
)
1634 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1636 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1637 sp
->cout_delta
+= len
;
1641 sess_local
[s
].cout
+= len
; // To send to master..
1642 sess_local
[s
].pout
++;
1646 // Helper routine for the TBF filters.
1647 // Used to send queued data in to the user!
1649 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1655 uint8_t b
[MAXETHER
+ 20];
1657 if (len
< 0 || len
> MAXETHER
)
1659 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1663 // Skip the tun header
1667 ip
= *(in_addr_t
*)(buf
+ 16);
1672 t
= session
[s
].tunnel
;
1675 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1677 // Add on L2TP header
1679 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1681 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1684 // Snooping this session.
1685 if (sp
->snoop_ip
&& sp
->snoop_port
)
1686 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1688 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1689 sp
->cout_delta
+= len
;
1693 sess_local
[s
].cout
+= len
; // To send to master..
1694 sess_local
[s
].pout
++;
1697 // add an AVP (16 bit)
1698 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1700 uint16_t l
= (m
? 0x8008 : 0x0008);
1701 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1702 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1703 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1704 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1708 // add an AVP (32 bit)
1709 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1711 uint16_t l
= (m
? 0x800A : 0x000A);
1712 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1713 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1714 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1715 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1719 // add an AVP (string)
1720 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1722 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1723 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1724 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1725 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1726 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1727 c
->length
+= 6 + strlen(val
);
1731 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1733 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1734 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1735 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1736 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1737 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1738 c
->length
+= 6 + len
;
1741 // new control connection
1742 static controlt
*controlnew(uint16_t mtype
)
1746 c
= malloc(sizeof(controlt
));
1750 controlfree
= c
->next
;
1754 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1756 control16(c
, 0, mtype
, 1);
1760 // send zero block if nothing is waiting
1762 static void controlnull(tunnelidt t
)
1765 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1768 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1769 *(uint16_t *) (buf
+ 2) = htons(12); // length
1770 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1771 *(uint16_t *) (buf
+ 6) = htons(0); // session
1772 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1773 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1774 tunnelsend(buf
, 12, t
);
1777 // add a control message to a tunnel, and send if within window
1778 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1780 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1781 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1782 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1783 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1784 tunnel
[t
].ns
++; // advance sequence
1785 // link in message in to queue
1786 if (tunnel
[t
].controlc
)
1787 tunnel
[t
].controle
->next
= c
;
1789 tunnel
[t
].controls
= c
;
1791 tunnel
[t
].controle
= c
;
1792 tunnel
[t
].controlc
++;
1794 // send now if space in window
1795 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1797 tunnel
[t
].try = 0; // first send
1798 tunnelsend(c
->buf
, c
->length
, t
);
1803 // Throttle or Unthrottle a session
1805 // Throttle the data from/to through a session to no more than
1806 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1809 // If either value is -1, the current value is retained for that
1812 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1814 if (!session
[s
].opened
)
1815 return; // No-one home.
1817 if (!*session
[s
].user
)
1818 return; // User not logged in
1822 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1823 if (session
[s
].tbf_in
)
1824 free_tbf(session
[s
].tbf_in
);
1827 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1829 session
[s
].tbf_in
= 0;
1831 session
[s
].throttle_in
= rate_in
;
1836 int bytes
= rate_out
* 1024 / 8;
1837 if (session
[s
].tbf_out
)
1838 free_tbf(session
[s
].tbf_out
);
1841 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1843 session
[s
].tbf_out
= 0;
1845 session
[s
].throttle_out
= rate_out
;
1849 // add/remove filters from session (-1 = no change)
1850 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1852 if (!session
[s
].opened
)
1853 return; // No-one home.
1855 if (!*session
[s
].user
)
1856 return; // User not logged in
1859 if (filter_in
> MAXFILTER
) filter_in
= -1;
1860 if (filter_out
> MAXFILTER
) filter_out
= -1;
1861 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1862 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1866 if (session
[s
].filter_in
)
1867 ip_filters
[session
[s
].filter_in
- 1].used
--;
1870 ip_filters
[filter_in
- 1].used
++;
1872 session
[s
].filter_in
= filter_in
;
1875 if (filter_out
>= 0)
1877 if (session
[s
].filter_out
)
1878 ip_filters
[session
[s
].filter_out
- 1].used
--;
1881 ip_filters
[filter_out
- 1].used
++;
1883 session
[s
].filter_out
= filter_out
;
1887 // start tidy shutdown of session
1888 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1890 int walled_garden
= session
[s
].walled_garden
;
1891 bundleidt b
= session
[s
].bundle
;
1892 //delete routes only for last session in bundle (in case of MPPP)
1893 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1895 CSTAT(sessionshutdown
);
1897 if (!session
[s
].opened
)
1899 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1900 return; // not a live session
1903 if (!session
[s
].die
)
1905 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1906 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1907 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1908 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1911 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1913 // RADIUS Stop message
1914 uint16_t r
= radiusnew(s
);
1917 // stop, if not already trying
1918 if (radius
[r
].state
!= RADIUSSTOP
)
1920 radius
[r
].term_cause
= term_cause
;
1921 radius
[r
].term_msg
= reason
;
1922 radiussend(r
, RADIUSSTOP
);
1926 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1928 // Save counters to dump to accounting file
1929 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1930 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1934 { // IP allocated, clear and unroute
1937 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1939 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
1940 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
1943 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
1944 session
[s
].route
[r
].ip
= 0;
1947 if (session
[s
].ip_pool_index
== -1) // static ip
1949 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1955 // unroute IPv6, if setup
1956 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
1957 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1961 // This session was part of a bundle
1962 bundle
[b
].num_of_links
--;
1963 LOG(3, s
, 0, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
1964 if(bundle
[b
].num_of_links
== 0)
1967 LOG(3, s
, 0, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
1971 // Adjust the members array to accomodate the new change
1972 uint8_t mem_num
= 0;
1973 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
1974 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
1977 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
1978 if(bundle
[b
].members
[ml
] == s
)
1983 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
1984 LOG(3, s
, 0, "MPPP: Adjusted member links array\n");
1987 cluster_send_bundle(b
);
1991 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1992 throttle_session(s
, 0, 0);
1996 controlt
*c
= controlnew(14); // sending CDN
2000 *(uint16_t *) buf
= htons(cdn_result
);
2001 *(uint16_t *) (buf
+2) = htons(cdn_error
);
2002 controlb(c
, 1, buf
, 4, 1);
2005 control16(c
, 1, cdn_result
, 1);
2007 control16(c
, 14, s
, 1); // assigned session (our end)
2008 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2011 // update filter refcounts
2012 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2013 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2016 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2017 sess_local
[s
].lcp
.restart
= 0;
2018 sess_local
[s
].ipcp
.restart
= 0;
2019 sess_local
[s
].ipv6cp
.restart
= 0;
2020 sess_local
[s
].ccp
.restart
= 0;
2022 cluster_send_session(s
);
2025 void sendipcp(sessionidt s
, tunnelidt t
)
2027 uint8_t buf
[MAXETHER
];
2031 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2033 if (!session
[s
].unique_id
)
2035 if (!++last_id
) ++last_id
; // skip zero
2036 session
[s
].unique_id
= last_id
;
2039 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2043 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2044 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2045 q
[4] = 3; // ip address option
2046 q
[5] = 6; // option length
2047 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2048 config
->bind_address
? config
->bind_address
:
2049 my_address
; // send my IP
2051 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2052 restart_timer(s
, ipcp
);
2055 void sendipv6cp(sessionidt s
, tunnelidt t
)
2057 uint8_t buf
[MAXETHER
];
2061 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2063 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2067 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2068 // only send one type
2070 *(uint16_t *) (q
+ 2) = htons(14);
2071 q
[4] = 1; // interface identifier option
2072 q
[5] = 10; // option length
2073 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2074 *(uint32_t *) (q
+ 10) = 0;
2077 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2078 restart_timer(s
, ipv6cp
);
2081 static void sessionclear(sessionidt s
)
2083 memset(&session
[s
], 0, sizeof(session
[s
]));
2084 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2085 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2087 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2088 session
[s
].next
= sessionfree
;
2092 // kill a session now
2093 void sessionkill(sessionidt s
, char *reason
)
2097 if (!session
[s
].opened
) // not alive
2100 if (session
[s
].next
)
2102 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2106 if (!session
[s
].die
)
2107 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2109 if (sess_local
[s
].radius
)
2110 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2112 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2114 cluster_send_session(s
);
2117 static void tunnelclear(tunnelidt t
)
2120 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2121 tunnel
[t
].state
= TUNNELFREE
;
2124 static void bundleclear(bundleidt b
)
2127 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2128 bundle
[b
].state
= BUNDLEFREE
;
2131 // kill a tunnel now
2132 static void tunnelkill(tunnelidt t
, char *reason
)
2139 tunnel
[t
].state
= TUNNELDIE
;
2141 // free control messages
2142 while ((c
= tunnel
[t
].controls
))
2144 controlt
* n
= c
->next
;
2145 tunnel
[t
].controls
= n
;
2146 tunnel
[t
].controlc
--;
2147 c
->next
= controlfree
;
2151 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2152 if (session
[s
].tunnel
== t
)
2153 sessionkill(s
, reason
);
2157 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2158 cli_tunnel_actions
[t
].action
= 0;
2159 cluster_send_tunnel(t
);
2162 // shut down a tunnel cleanly
2163 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2167 CSTAT(tunnelshutdown
);
2169 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2171 // never set up, can immediately kill
2172 tunnelkill(t
, reason
);
2175 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2178 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2179 if (session
[s
].tunnel
== t
)
2180 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2182 tunnel
[t
].state
= TUNNELDIE
;
2183 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2184 cluster_send_tunnel(t
);
2185 // TBA - should we wait for sessions to stop?
2188 controlt
*c
= controlnew(4); // sending StopCCN
2193 *(uint16_t *) buf
= htons(result
);
2194 *(uint16_t *) (buf
+2) = htons(error
);
2197 int m
= strlen(msg
);
2198 if (m
+ 4 > sizeof(buf
))
2199 m
= sizeof(buf
) - 4;
2201 memcpy(buf
+4, msg
, m
);
2205 controlb(c
, 1, buf
, l
, 1);
2208 control16(c
, 1, result
, 1);
2210 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2211 controladd(c
, 0, t
); // send the message
2215 // read and process packet on tunnel (UDP)
2216 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2218 uint8_t *chapresponse
= NULL
;
2219 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2220 uint8_t *p
= buf
+ 2;
2227 LOG_HEX(5, "UDP Data", buf
, len
);
2228 STAT(tunnel_rx_packets
);
2229 INC_STAT(tunnel_rx_bytes
, len
);
2232 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2233 STAT(tunnel_rx_errors
);
2236 if ((buf
[1] & 0x0F) != 2)
2238 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2239 STAT(tunnel_rx_errors
);
2244 l
= ntohs(*(uint16_t *) p
);
2247 t
= ntohs(*(uint16_t *) p
);
2249 s
= ntohs(*(uint16_t *) p
);
2251 if (s
>= MAXSESSION
)
2253 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2254 STAT(tunnel_rx_errors
);
2259 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2260 STAT(tunnel_rx_errors
);
2265 ns
= ntohs(*(uint16_t *) p
);
2267 nr
= ntohs(*(uint16_t *) p
);
2272 uint16_t o
= ntohs(*(uint16_t *) p
);
2277 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2278 STAT(tunnel_rx_errors
);
2283 // used to time out old tunnels
2284 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2285 tunnel
[t
].lastrec
= time_now
;
2289 uint16_t message
= 0xFFFF; // message type
2291 uint8_t mandatory
= 0;
2292 uint16_t asession
= 0; // assigned session
2293 uint32_t amagic
= 0; // magic number
2294 uint8_t aflags
= 0; // flags from last LCF
2295 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2296 char called
[MAXTEL
] = ""; // called number
2297 char calling
[MAXTEL
] = ""; // calling number
2299 if (!config
->cluster_iam_master
)
2301 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2305 // control messages must have bits 0x80|0x40|0x08
2306 // (type, length and sequence) set, and bits 0x02|0x01
2307 // (offset and priority) clear
2308 if ((*buf
& 0xCB) != 0xC8)
2310 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2311 STAT(tunnel_rx_errors
);
2315 // check for duplicate tunnel open message
2321 // Is this a duplicate of the first packet? (SCCRQ)
2323 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2325 if (tunnel
[i
].state
!= TUNNELOPENING
||
2326 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2327 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2330 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2335 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2336 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2338 // if no tunnel specified, assign one
2341 if (!(t
= new_tunnel()))
2343 LOG(1, 0, 0, "No more tunnels\n");
2344 STAT(tunnel_overflow
);
2348 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2349 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2350 tunnel
[t
].window
= 4; // default window
2351 STAT(tunnel_created
);
2352 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2353 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2356 // If the 'ns' just received is not the 'nr' we're
2357 // expecting, just send an ack and drop it.
2359 // if 'ns' is less, then we got a retransmitted packet.
2360 // if 'ns' is greater than missed a packet. Either way
2361 // we should ignore it.
2362 if (ns
!= tunnel
[t
].nr
)
2364 // is this the sequence we were expecting?
2365 STAT(tunnel_rx_errors
);
2366 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2367 t
, ns
, tunnel
[t
].nr
);
2369 if (l
) // Is this not a ZLB?
2374 // check sequence of this message
2376 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2377 // some to clear maybe?
2378 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2380 controlt
*c
= tunnel
[t
].controls
;
2381 tunnel
[t
].controls
= c
->next
;
2382 tunnel
[t
].controlc
--;
2383 c
->next
= controlfree
;
2386 tunnel
[t
].try = 0; // we have progress
2389 // receiver advance (do here so quoted correctly in any sends below)
2390 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2391 if (skip
< 0) skip
= 0;
2392 if (skip
< tunnel
[t
].controlc
)
2394 // some control packets can now be sent that were previous stuck out of window
2395 int tosend
= tunnel
[t
].window
- skip
;
2396 controlt
*c
= tunnel
[t
].controls
;
2404 tunnel
[t
].try = 0; // first send
2405 tunnelsend(c
->buf
, c
->length
, t
);
2410 if (!tunnel
[t
].controlc
)
2411 tunnel
[t
].retry
= 0; // caught up
2414 { // if not a null message
2419 // Default disconnect cause/message on receipt of CDN. Set to
2420 // more specific value from attribute 1 (result code) or 46
2421 // (disconnect cause) if present below.
2422 int disc_cause_set
= 0;
2423 int disc_cause
= TERM_NAS_REQUEST
;
2424 char const *disc_reason
= "Closed (Received CDN).";
2427 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2429 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2436 LOG(1, s
, t
, "Invalid length in AVP\n");
2437 STAT(tunnel_rx_errors
);
2442 if (flags
& 0x3C) // reserved bits, should be clear
2444 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2446 result
= 2; // general error
2447 error
= 3; // reserved field non-zero
2452 if (*(uint16_t *) (b
))
2454 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2456 result
= 2; // general error
2457 error
= 6; // generic vendor-specific error
2458 msg
= "unsupported vendor-specific";
2462 mtype
= ntohs(*(uint16_t *) (b
));
2470 // handle hidden AVPs
2471 if (!*config
->l2tp_secret
)
2473 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2475 result
= 2; // general error
2476 error
= 6; // generic vendor-specific error
2477 msg
= "secret not specified";
2480 if (!session
[s
].random_vector_length
)
2482 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2484 result
= 2; // general error
2485 error
= 6; // generic
2486 msg
= "no random vector";
2491 LOG(2, s
, t
, "Short hidden AVP.\n");
2493 result
= 2; // general error
2494 error
= 2; // length is wrong
2500 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2502 orig_len
= ntohs(*(uint16_t *) b
);
2503 if (orig_len
> n
+ 2)
2505 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2509 result
= 2; // general error
2510 error
= 2; // length is wrong
2519 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2520 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2524 case 0: // message type
2525 message
= ntohs(*(uint16_t *) b
);
2526 mandatory
= flags
& 0x80;
2527 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2529 case 1: // result code
2531 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2532 char const *resdesc
= "(unknown)";
2533 char const *errdesc
= NULL
;
2538 resdesc
= l2tp_stopccn_result_code(rescode
);
2539 cause
= TERM_LOST_SERVICE
;
2541 else if (message
== 14)
2543 resdesc
= l2tp_cdn_result_code(rescode
);
2545 cause
= TERM_LOST_CARRIER
;
2547 cause
= TERM_ADMIN_RESET
;
2550 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2553 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2554 errdesc
= l2tp_error_code(errcode
);
2555 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2558 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2560 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2562 disc_cause_set
= mtype
;
2563 disc_reason
= errdesc
? errdesc
: resdesc
;
2570 case 2: // protocol version
2572 version
= ntohs(*(uint16_t *) (b
));
2573 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2574 if (version
&& version
!= 0x0100)
2575 { // allow 0.0 and 1.0
2576 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2578 result
= 5; // unspported protocol version
2579 error
= 0x0100; // supported version
2585 case 3: // framing capabilities
2587 case 4: // bearer capabilities
2589 case 5: // tie breaker
2590 // We never open tunnels, so we don't care about tie breakers
2592 case 6: // firmware revision
2594 case 7: // host name
2595 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2596 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2597 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2598 // TBA - to send to RADIUS
2600 case 8: // vendor name
2601 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2602 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2603 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2605 case 9: // assigned tunnel
2606 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2607 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2609 case 10: // rx window
2610 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2611 if (!tunnel
[t
].window
)
2612 tunnel
[t
].window
= 1; // window of 0 is silly
2613 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2615 case 11: // Challenge
2617 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2618 build_chap_response(b
, 2, n
, &chapresponse
);
2621 case 13: // Response
2622 // Why did they send a response? We never challenge.
2623 LOG(2, s
, t
, " received unexpected challenge response\n");
2626 case 14: // assigned session
2627 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2628 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2630 case 15: // call serial number
2631 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2633 case 18: // bearer type
2634 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2637 case 19: // framing type
2638 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2641 case 21: // called number
2642 memset(called
, 0, sizeof(called
));
2643 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2644 LOG(4, s
, t
, " Called <%s>\n", called
);
2646 case 22: // calling number
2647 memset(calling
, 0, sizeof(calling
));
2648 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2649 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2653 case 24: // tx connect speed
2656 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2660 // AS5300s send connect speed as a string
2662 memset(tmp
, 0, sizeof(tmp
));
2663 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2664 session
[s
].tx_connect_speed
= atol(tmp
);
2666 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2668 case 38: // rx connect speed
2671 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2675 // AS5300s send connect speed as a string
2677 memset(tmp
, 0, sizeof(tmp
));
2678 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2679 session
[s
].rx_connect_speed
= atol(tmp
);
2681 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2683 case 25: // Physical Channel ID
2685 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2686 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2689 case 29: // Proxy Authentication Type
2691 uint16_t atype
= ntohs(*(uint16_t *)b
);
2692 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2695 case 30: // Proxy Authentication Name
2698 memset(authname
, 0, sizeof(authname
));
2699 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2700 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2704 case 31: // Proxy Authentication Challenge
2706 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2709 case 32: // Proxy Authentication ID
2711 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2712 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2715 case 33: // Proxy Authentication Response
2716 LOG(4, s
, t
, " Proxy Auth Response\n");
2718 case 27: // last sent lcp
2719 { // find magic number
2720 uint8_t *p
= b
, *e
= p
+ n
;
2721 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2723 if (*p
== 5 && p
[1] == 6) // Magic-Number
2724 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2725 else if (*p
== 7) // Protocol-Field-Compression
2726 aflags
|= SESSION_PFC
;
2727 else if (*p
== 8) // Address-and-Control-Field-Compression
2728 aflags
|= SESSION_ACFC
;
2733 case 28: // last recv lcp confreq
2735 case 26: // Initial Received LCP CONFREQ
2737 case 39: // seq required - we control it as an LNS anyway...
2739 case 36: // Random Vector
2740 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2741 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2742 if (n
> sizeof(session
[s
].random_vector
))
2743 n
= sizeof(session
[s
].random_vector
);
2744 memcpy(session
[s
].random_vector
, b
, n
);
2745 session
[s
].random_vector_length
= n
;
2747 case 46: // ppp disconnect cause
2750 uint16_t code
= ntohs(*(uint16_t *) b
);
2751 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2752 uint8_t dir
= *(b
+ 4);
2754 LOG(4, s
, t
, " PPP disconnect cause "
2755 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2756 code
, proto
, dir
, n
- 5, b
+ 5);
2758 disc_cause_set
= mtype
;
2762 case 1: // admin disconnect
2763 disc_cause
= TERM_ADMIN_RESET
;
2764 disc_reason
= "Administrative disconnect";
2766 case 3: // lcp terminate
2767 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2768 disc_cause
= TERM_USER_REQUEST
;
2769 disc_reason
= "Normal disconnection";
2771 case 4: // compulsory encryption unavailable
2772 if (dir
!= 1) break; // 1=refused by peer, 2=local
2773 disc_cause
= TERM_USER_ERROR
;
2774 disc_reason
= "Compulsory encryption refused";
2776 case 5: // lcp: fsm timeout
2777 disc_cause
= TERM_PORT_ERROR
;
2778 disc_reason
= "LCP: FSM timeout";
2780 case 6: // lcp: no recognisable lcp packets received
2781 disc_cause
= TERM_PORT_ERROR
;
2782 disc_reason
= "LCP: no recognisable LCP packets";
2784 case 7: // lcp: magic-no error (possibly looped back)
2785 disc_cause
= TERM_PORT_ERROR
;
2786 disc_reason
= "LCP: magic-no error (possible loop)";
2788 case 8: // lcp: echo request timeout
2789 disc_cause
= TERM_PORT_ERROR
;
2790 disc_reason
= "LCP: echo request timeout";
2792 case 13: // auth: fsm timeout
2793 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2794 disc_reason
= "Authentication: FSM timeout";
2796 case 15: // auth: unacceptable auth protocol
2797 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2798 disc_reason
= "Unacceptable authentication protocol";
2800 case 16: // auth: authentication failed
2801 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2802 disc_reason
= "Authentication failed";
2804 case 17: // ncp: fsm timeout
2805 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2806 disc_reason
= "NCP: FSM timeout";
2808 case 18: // ncp: no ncps available
2809 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2810 disc_reason
= "NCP: no NCPs available";
2812 case 19: // ncp: failure to converge on acceptable address
2813 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2814 disc_reason
= (dir
== 1)
2815 ? "NCP: too many Configure-Naks received from peer"
2816 : "NCP: too many Configure-Naks sent to peer";
2818 case 20: // ncp: user not permitted to use any address
2819 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2820 disc_reason
= (dir
== 1)
2821 ? "NCP: local link address not acceptable to peer"
2822 : "NCP: remote link address not acceptable";
2829 static char e
[] = "unknown AVP 0xXXXX";
2830 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2832 result
= 2; // general error
2833 error
= 8; // unknown mandatory AVP
2834 sprintf((msg
= e
) + 14, "%04x", mtype
);
2841 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2845 case 1: // SCCRQ - Start Control Connection Request
2846 tunnel
[t
].state
= TUNNELOPENING
;
2847 if (main_quit
!= QUIT_SHUTDOWN
)
2849 controlt
*c
= controlnew(2); // sending SCCRP
2850 control16(c
, 2, version
, 1); // protocol version
2851 control32(c
, 3, 3, 1); // framing
2852 controls(c
, 7, hostname
, 1); // host name
2853 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2854 control16(c
, 9, t
, 1); // assigned tunnel
2855 controladd(c
, 0, t
); // send the resply
2859 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2863 tunnel
[t
].state
= TUNNELOPEN
;
2864 tunnel
[t
].lastrec
= time_now
;
2867 tunnel
[t
].state
= TUNNELOPEN
;
2868 tunnel
[t
].lastrec
= time_now
;
2869 controlnull(t
); // ack
2872 controlnull(t
); // ack
2873 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2876 controlnull(t
); // simply ACK
2888 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2890 controlt
*c
= controlnew(11); // ICRP
2893 sessionfree
= session
[s
].next
;
2894 memset(&session
[s
], 0, sizeof(session
[s
]));
2896 if (s
> config
->cluster_highest_sessionid
)
2897 config
->cluster_highest_sessionid
= s
;
2899 session
[s
].opened
= time_now
;
2900 session
[s
].tunnel
= t
;
2901 session
[s
].far
= asession
;
2902 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2903 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2904 control16(c
, 14, s
, 1); // assigned session
2905 controladd(c
, asession
, t
); // send the reply
2907 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2908 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2910 session
[s
].ppp
.phase
= Establish
;
2911 session
[s
].ppp
.lcp
= Starting
;
2913 STAT(session_created
);
2918 controlt
*c
= controlnew(14); // CDN
2921 STAT(session_overflow
);
2922 LOG(1, 0, t
, "No free sessions\n");
2923 control16(c
, 1, 4, 0); // temporary lack of resources
2926 control16(c
, 1, 2, 7); // shutting down, try another
2928 controladd(c
, asession
, t
); // send the message
2935 if (amagic
== 0) amagic
= time_now
;
2936 session
[s
].magic
= amagic
; // set magic number
2937 session
[s
].flags
= aflags
; // set flags received
2938 session
[s
].mru
= PPPoE_MRU
; // default
2939 controlnull(t
); // ack
2942 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
2943 sess_local
[s
].ppp_mru
= MRU
;
2945 // Set multilink options before sending initial LCP packet
2946 sess_local
[s
].mp_mrru
= 1614;
2947 sess_local
[s
].mp_epdis
= config
->bind_address
? config
->bind_address
: my_address
;
2950 change_state(s
, lcp
, RequestSent
);
2954 controlnull(t
); // ack
2955 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
2958 LOG(1, s
, t
, "Missing message type\n");
2961 STAT(tunnel_rx_errors
);
2963 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2965 LOG(1, s
, t
, "Unknown message type %u\n", message
);
2968 if (chapresponse
) free(chapresponse
);
2969 cluster_send_tunnel(t
);
2973 LOG(4, s
, t
, " Got a ZLB ack\n");
2980 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
2981 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
2982 { // HDLC address header, discard
2988 LOG(1, s
, t
, "Short ppp length %d\n", l
);
2989 STAT(tunnel_rx_errors
);
2999 proto
= ntohs(*(uint16_t *) p
);
3004 if (s
&& !session
[s
].opened
) // Is something wrong??
3006 if (!config
->cluster_iam_master
)
3008 // Pass it off to the master to deal with..
3009 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3014 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3015 STAT(tunnel_rx_errors
);
3019 if (proto
== PPPPAP
)
3021 session
[s
].last_packet
= time_now
;
3022 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3023 processpap(s
, t
, p
, l
);
3025 else if (proto
== PPPCHAP
)
3027 session
[s
].last_packet
= time_now
;
3028 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3029 processchap(s
, t
, p
, l
);
3031 else if (proto
== PPPLCP
)
3033 session
[s
].last_packet
= time_now
;
3034 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3035 processlcp(s
, t
, p
, l
);
3037 else if (proto
== PPPIPCP
)
3039 session
[s
].last_packet
= time_now
;
3040 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3041 processipcp(s
, t
, p
, l
);
3043 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3045 session
[s
].last_packet
= time_now
;
3046 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3047 processipv6cp(s
, t
, p
, l
);
3049 else if (proto
== PPPCCP
)
3051 session
[s
].last_packet
= time_now
;
3052 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3053 processccp(s
, t
, p
, l
);
3055 else if (proto
== PPPIP
)
3059 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3060 return; // closing session, PPP not processed
3063 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3064 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3066 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3070 processipin(s
, t
, p
, l
);
3072 else if (proto
== PPPMP
)
3076 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3077 return; // closing session, PPP not processed
3080 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3081 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3083 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3087 processmpin(s
, t
, p
, l
);
3089 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3093 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3094 return; // closing session, PPP not processed
3097 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3098 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3100 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3104 processipv6in(s
, t
, p
, l
);
3106 else if (session
[s
].ppp
.lcp
== Opened
)
3108 session
[s
].last_packet
= time_now
;
3109 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3110 protoreject(s
, t
, p
, l
, proto
);
3114 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3115 proto
, ppp_state(session
[s
].ppp
.lcp
));
3120 // read and process packet on tun
3121 static void processtun(uint8_t * buf
, int len
)
3123 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3124 STAT(tun_rx_packets
);
3125 INC_STAT(tun_rx_bytes
, len
);
3133 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3134 STAT(tun_rx_errors
);
3138 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3139 processipout(buf
, len
);
3140 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3141 && config
->ipv6_prefix
.s6_addr
[0])
3142 processipv6out(buf
, len
);
3147 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3148 // that we look at the whole of the tunnel, radius and session tables
3150 static void regular_cleanups(double period
)
3152 // Next tunnel, radius and session to check for actions on.
3153 static tunnelidt t
= 0;
3155 static sessionidt s
= 0;
3168 // divide up tables into slices based on the last run
3169 t_slice
= config
->cluster_highest_tunnelid
* period
;
3170 r_slice
= (MAXRADIUS
- 1) * period
;
3171 s_slice
= config
->cluster_highest_sessionid
* period
;
3175 else if (t_slice
> config
->cluster_highest_tunnelid
)
3176 t_slice
= config
->cluster_highest_tunnelid
;
3180 else if (r_slice
> (MAXRADIUS
- 1))
3181 r_slice
= MAXRADIUS
- 1;
3185 else if (s_slice
> config
->cluster_highest_sessionid
)
3186 s_slice
= config
->cluster_highest_sessionid
;
3188 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3190 for (i
= 0; i
< t_slice
; i
++)
3193 if (t
> config
->cluster_highest_tunnelid
)
3196 // check for expired tunnels
3197 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3199 STAT(tunnel_timeout
);
3200 tunnelkill(t
, "Expired");
3204 // check for message resend
3205 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3207 // resend pending messages as timeout on reply
3208 if (tunnel
[t
].retry
<= TIME
)
3210 controlt
*c
= tunnel
[t
].controls
;
3211 uint16_t w
= tunnel
[t
].window
;
3212 tunnel
[t
].try++; // another try
3213 if (tunnel
[t
].try > 5)
3214 tunnelkill(t
, "Timeout on control message"); // game over
3218 tunnelsend(c
->buf
, c
->length
, t
);
3226 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3228 controlt
*c
= controlnew(6); // sending HELLO
3229 controladd(c
, 0, t
); // send the message
3230 LOG(3, 0, t
, "Sending HELLO message\n");
3234 // Check for tunnel changes requested from the CLI
3235 if ((a
= cli_tunnel_actions
[t
].action
))
3237 cli_tunnel_actions
[t
].action
= 0;
3238 if (a
& CLI_TUN_KILL
)
3240 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3241 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3247 for (i
= 0; i
< r_slice
; i
++)
3253 if (!radius
[r
].state
)
3256 if (radius
[r
].retry
<= TIME
)
3263 for (i
= 0; i
< s_slice
; i
++)
3266 if (s
> config
->cluster_highest_sessionid
)
3269 if (!session
[s
].opened
) // Session isn't in use
3272 // check for expired sessions
3275 if (session
[s
].die
<= TIME
)
3277 sessionkill(s
, "Expired");
3284 if (sess_local
[s
].lcp
.restart
<= time_now
)
3286 int next_state
= session
[s
].ppp
.lcp
;
3287 switch (session
[s
].ppp
.lcp
)
3291 next_state
= RequestSent
;
3294 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3296 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3297 sendlcp(s
, session
[s
].tunnel
);
3298 change_state(s
, lcp
, next_state
);
3302 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3303 STAT(session_timeout
);
3313 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3315 int next_state
= session
[s
].ppp
.ipcp
;
3316 switch (session
[s
].ppp
.ipcp
)
3320 next_state
= RequestSent
;
3323 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3325 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3326 sendipcp(s
, session
[s
].tunnel
);
3327 change_state(s
, ipcp
, next_state
);
3331 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3332 STAT(session_timeout
);
3342 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3344 int next_state
= session
[s
].ppp
.ipv6cp
;
3345 switch (session
[s
].ppp
.ipv6cp
)
3349 next_state
= RequestSent
;
3352 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3354 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3355 sendipv6cp(s
, session
[s
].tunnel
);
3356 change_state(s
, ipv6cp
, next_state
);
3360 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3361 change_state(s
, ipv6cp
, Stopped
);
3368 if (sess_local
[s
].ccp
.restart
<= time_now
)
3370 int next_state
= session
[s
].ppp
.ccp
;
3371 switch (session
[s
].ppp
.ccp
)
3375 next_state
= RequestSent
;
3378 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3380 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3381 sendccp(s
, session
[s
].tunnel
);
3382 change_state(s
, ccp
, next_state
);
3386 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3387 change_state(s
, ccp
, Stopped
);
3394 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3395 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3397 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3398 STAT(session_timeout
);
3403 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3404 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3405 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3407 uint8_t b
[MAXETHER
];
3409 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3413 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3414 *(uint16_t *)(q
+ 2) = htons(8); // Length
3415 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3417 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3418 (int)(time_now
- session
[s
].last_packet
));
3419 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3420 sess_local
[s
].last_echo
= time_now
;
3424 // Drop sessions who have reached session_timeout seconds
3425 if (session
[s
].session_timeout
)
3427 bundleidt bid
= session
[s
].bundle
;
3430 if (time_now
- bundle
[bid
].last_check
>= 1)
3432 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3433 bundle
[bid
].last_check
= time_now
;
3434 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3437 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3439 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3446 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3448 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3454 // Drop sessions who have reached idle_timeout seconds
3455 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3457 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3458 STAT(session_timeout
);
3463 // Check for actions requested from the CLI
3464 if ((a
= cli_session_actions
[s
].action
))
3468 cli_session_actions
[s
].action
= 0;
3469 if (a
& CLI_SESS_KILL
)
3471 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3472 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3473 a
= 0; // dead, no need to check for other actions
3477 if (a
& CLI_SESS_NOSNOOP
)
3479 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3480 session
[s
].snoop_ip
= 0;
3481 session
[s
].snoop_port
= 0;
3485 else if (a
& CLI_SESS_SNOOP
)
3487 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3488 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3489 cli_session_actions
[s
].snoop_port
);
3491 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3492 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3497 if (a
& CLI_SESS_NOTHROTTLE
)
3499 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3500 throttle_session(s
, 0, 0);
3504 else if (a
& CLI_SESS_THROTTLE
)
3506 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3507 cli_session_actions
[s
].throttle_in
,
3508 cli_session_actions
[s
].throttle_out
);
3510 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3515 if (a
& CLI_SESS_NOFILTER
)
3517 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3518 filter_session(s
, 0, 0);
3522 else if (a
& CLI_SESS_FILTER
)
3524 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3525 cli_session_actions
[s
].filter_in
,
3526 cli_session_actions
[s
].filter_out
);
3528 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3534 cluster_send_session(s
);
3537 // RADIUS interim accounting
3538 if (config
->radius_accounting
&& config
->radius_interim
> 0
3539 && session
[s
].ip
&& !session
[s
].walled_garden
3540 && !sess_local
[s
].radius
// RADIUS already in progress
3541 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3542 && session
[s
].flags
& SESSION_STARTED
)
3544 int rad
= radiusnew(s
);
3547 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3548 STAT(radius_overflow
);
3552 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3553 session
[s
].user
, session
[s
].unique_id
);
3555 radiussend(rad
, RADIUSINTERIM
);
3556 sess_local
[s
].last_interim
= time_now
;
3561 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3562 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3566 // Are we in the middle of a tunnel update, or radius
3569 static int still_busy(void)
3572 static clockt last_talked
= 0;
3573 static clockt start_busy_wait
= 0;
3575 if (!config
->cluster_iam_master
)
3578 static time_t stopped_bgp
= 0;
3583 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3585 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3586 if (bgp_peers
[i
].state
== Established
)
3587 bgp_stop(&bgp_peers
[i
]);
3589 stopped_bgp
= time_now
;
3591 // we don't want to become master
3592 cluster_send_ping(0);
3597 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
3605 if (main_quit
== QUIT_SHUTDOWN
)
3607 static int dropped
= 0;
3612 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3613 for (i
= 1; i
< MAXTUNNEL
; i
++)
3614 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3615 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3621 if (start_busy_wait
== 0)
3622 start_busy_wait
= TIME
;
3624 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3626 if (!tunnel
[i
].controlc
)
3629 if (last_talked
!= TIME
)
3631 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3637 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3638 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3640 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3644 for (i
= 1; i
< MAXRADIUS
; i
++)
3646 if (radius
[i
].state
== RADIUSNULL
)
3648 if (radius
[i
].state
== RADIUSWAIT
)
3651 if (last_talked
!= TIME
)
3653 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3663 # include <sys/epoll.h>
3665 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3666 # include "fake_epoll.h"
3669 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3672 // additional polled fds
3674 # define EXTRA_FDS BGP_NUM_PEERS
3676 # define EXTRA_FDS 0
3679 // main loop - gets packets on tun or udp and processes them
3680 static void mainloop(void)
3684 clockt next_cluster_ping
= 0; // send initial ping immediately
3685 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3686 int maxevent
= sizeof(events
)/sizeof(*events
);
3688 if ((epollfd
= epoll_create(maxevent
)) < 0)
3690 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3694 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3695 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3697 /* setup our fds to poll for input */
3699 static struct event_data d
[BASE_FDS
];
3700 struct epoll_event e
;
3707 d
[i
].type
= FD_TYPE_CLI
;
3708 e
.data
.ptr
= &d
[i
++];
3709 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3712 d
[i
].type
= FD_TYPE_CLUSTER
;
3713 e
.data
.ptr
= &d
[i
++];
3714 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3716 d
[i
].type
= FD_TYPE_TUN
;
3717 e
.data
.ptr
= &d
[i
++];
3718 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3720 d
[i
].type
= FD_TYPE_UDP
;
3721 e
.data
.ptr
= &d
[i
++];
3722 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3724 d
[i
].type
= FD_TYPE_CONTROL
;
3725 e
.data
.ptr
= &d
[i
++];
3726 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3728 d
[i
].type
= FD_TYPE_DAE
;
3729 e
.data
.ptr
= &d
[i
++];
3730 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3732 d
[i
].type
= FD_TYPE_NETLINK
;
3733 e
.data
.ptr
= &d
[i
++];
3734 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3738 signal(SIGPIPE
, SIG_IGN
);
3739 bgp_setup(config
->as_number
);
3740 if (config
->bind_address
)
3741 bgp_add_route(config
->bind_address
, 0xffffffff);
3743 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3745 if (config
->neighbour
[i
].name
[0])
3746 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3747 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3748 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3752 while (!main_quit
|| still_busy())
3762 config
->reload_config
++;
3765 if (config
->reload_config
)
3767 config
->reload_config
= 0;
3775 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3776 STAT(select_called
);
3781 if (errno
== EINTR
||
3782 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3785 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3791 struct sockaddr_in addr
;
3792 struct in_addr local
;
3797 int cluster_ready
= 0;
3800 int cluster_pkts
= 0;
3802 uint32_t bgp_events
[BGP_NUM_PEERS
];
3803 memset(bgp_events
, 0, sizeof(bgp_events
));
3806 for (c
= n
, i
= 0; i
< c
; i
++)
3808 struct event_data
*d
= events
[i
].data
.ptr
;
3812 case FD_TYPE_CLI
: // CLI connections
3816 alen
= sizeof(addr
);
3817 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3823 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3829 // these are handled below, with multiple interleaved reads
3830 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3831 case FD_TYPE_TUN
: tun_ready
++; break;
3832 case FD_TYPE_UDP
: udp_ready
++; break;
3834 case FD_TYPE_CONTROL
: // nsctl commands
3835 alen
= sizeof(addr
);
3836 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3837 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3841 case FD_TYPE_DAE
: // DAE requests
3842 alen
= sizeof(addr
);
3843 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3844 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3848 case FD_TYPE_RADIUS
: // RADIUS response
3849 alen
= sizeof(addr
);
3850 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3851 if (s
>= 0 && config
->cluster_iam_master
)
3853 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3854 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3855 processrad(buf
, s
, d
->index
);
3857 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3858 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3866 bgp_events
[d
->index
] = events
[i
].events
;
3871 case FD_TYPE_NETLINK
:
3873 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
3874 s
= netlink_recv(buf
, sizeof(buf
));
3875 if (nh
->nlmsg_type
== NLMSG_ERROR
)
3877 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
3880 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
3882 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
3887 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
3892 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
);
3898 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3903 bgp_process(bgp_events
);
3906 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3911 alen
= sizeof(addr
);
3912 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3914 processudp(buf
, s
, &addr
);
3927 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3942 alen
= sizeof(addr
);
3943 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3945 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3956 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3957 STAT(multi_read_used
);
3959 if (c
>= config
->multi_read_count
)
3961 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3962 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3964 STAT(multi_read_exceeded
);
3971 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
3973 // Log current traffic stats
3974 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3975 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3976 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
3977 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
3978 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
3980 udp_tx
= udp_rx
= 0;
3981 udp_rx_pkt
= eth_rx_pkt
= 0;
3982 eth_tx
= eth_rx
= 0;
3985 if (config
->dump_speed
)
3986 printf("%s\n", config
->bandwidth
);
3988 // Update the internal time counter
3989 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3993 struct param_timer p
= { time_now
};
3994 run_plugins(PLUGIN_TIMER
, &p
);
3998 // Runs on every machine (master and slaves).
3999 if (next_cluster_ping
<= TIME
)
4001 // Check to see which of the cluster is still alive..
4003 cluster_send_ping(basetime
); // Only does anything if we're a slave
4004 cluster_check_master(); // ditto.
4006 cluster_heartbeat(); // Only does anything if we're a master.
4007 cluster_check_slaves(); // ditto.
4009 master_update_counts(); // If we're a slave, send our byte counters to our master.
4011 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4012 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4014 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4017 if (!config
->cluster_iam_master
)
4020 // Run token bucket filtering queue..
4021 // Only run it every 1/10th of a second.
4023 static clockt last_run
= 0;
4024 if (last_run
!= TIME
)
4031 // Handle timeouts, retries etc.
4033 static double last_clean
= 0;
4037 TIME
= now(&this_clean
);
4038 diff
= this_clean
- last_clean
;
4040 // Run during idle time (after we've handled
4041 // all incoming packets) or every 1/10th sec
4042 if (!more
|| diff
> 0.1)
4044 regular_cleanups(diff
);
4045 last_clean
= this_clean
;
4049 if (*config
->accounting_dir
)
4051 static clockt next_acct
= 0;
4052 static clockt next_shut_acct
= 0;
4054 if (next_acct
<= TIME
)
4056 // Dump accounting data
4057 next_acct
= TIME
+ ACCT_TIME
;
4058 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4061 else if (next_shut_acct
<= TIME
)
4063 // Dump accounting data for shutdown sessions
4064 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4071 // Are we the master and shutting down??
4072 if (config
->cluster_iam_master
)
4073 cluster_heartbeat(); // Flush any queued changes..
4075 // Ok. Notify everyone we're shutting down. If we're
4076 // the master, this will force an election.
4077 cluster_send_ping(0);
4080 // Important!!! We MUST not process any packets past this point!
4081 LOG(1, 0, 0, "Shutdown complete\n");
4084 static void stripdomain(char *host
)
4088 if ((p
= strchr(host
, '.')))
4094 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4100 while (fgets(buf
, sizeof(buf
), resolv
))
4102 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4105 if (!isspace(buf
[6]))
4109 while (isspace(*b
)) b
++;
4114 while (*b
&& !isspace(*b
)) b
++;
4116 if (buf
[0] == 'd') // domain is canonical
4122 // first search line
4125 // hold, may be subsequent domain line
4126 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4137 int hl
= strlen(host
);
4138 int dl
= strlen(domain
);
4139 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4140 host
[hl
-dl
- 1] = 0;
4144 *p
= 0; // everything after first dot
4149 // Init data structures
4150 static void initdata(int optdebug
, char *optconfig
)
4154 if (!(config
= shared_malloc(sizeof(configt
))))
4156 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4160 memset(config
, 0, sizeof(configt
));
4161 time(&config
->start_time
);
4162 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4163 config
->debug
= optdebug
;
4164 config
->num_tbfs
= MAXTBFS
;
4165 config
->rl_rate
= 28; // 28kbps
4166 config
->cluster_mcast_ttl
= 1;
4167 config
->cluster_master_min_adv
= 1;
4168 config
->ppp_restart_time
= 3;
4169 config
->ppp_max_configure
= 10;
4170 config
->ppp_max_failure
= 5;
4171 config
->kill_timedout_sessions
= 1;
4172 strcpy(config
->random_device
, RANDOMDEVICE
);
4174 log_stream
= stderr
;
4177 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4179 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4182 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4185 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4187 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4190 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4192 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4195 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4197 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4200 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4202 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4205 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4207 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4211 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4213 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4217 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4219 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4223 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4225 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4229 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4231 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4234 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4236 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4238 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4241 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4243 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4245 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4248 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4250 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4251 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4252 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4253 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4254 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4256 // Put all the sessions on the free list marked as undefined.
4257 for (i
= 1; i
< MAXSESSION
; i
++)
4259 session
[i
].next
= i
+ 1;
4260 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4262 session
[MAXSESSION
- 1].next
= 0;
4265 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4266 for (i
= 1; i
< MAXTUNNEL
; i
++)
4267 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4269 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4270 bundle
[i
].state
= BUNDLEUNDEF
;
4275 // Grab my hostname unless it's been specified
4276 gethostname(hostname
, sizeof(hostname
));
4277 stripdomain(hostname
);
4280 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4283 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4285 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4291 static int assign_ip_address(sessionidt s
)
4295 time_t best_time
= time_now
;
4296 char *u
= session
[s
].user
;
4300 CSTAT(assign_ip_address
);
4302 for (i
= 1; i
< ip_pool_size
; i
++)
4304 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4307 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4314 if (ip_address_pool
[i
].last
< best_time
)
4317 if (!(best_time
= ip_address_pool
[i
].last
))
4318 break; // never used, grab this one
4324 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4328 session
[s
].ip
= ip_address_pool
[best
].address
;
4329 session
[s
].ip_pool_index
= best
;
4330 ip_address_pool
[best
].assigned
= 1;
4331 ip_address_pool
[best
].last
= time_now
;
4332 ip_address_pool
[best
].session
= s
;
4333 if (session
[s
].walled_garden
)
4334 /* Don't track addresses of users in walled garden (note: this
4335 means that their address isn't "sticky" even if they get
4337 ip_address_pool
[best
].user
[0] = 0;
4339 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4342 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4343 reuse
? "Reusing" : "Allocating", best
);
4348 static void free_ip_address(sessionidt s
)
4350 int i
= session
[s
].ip_pool_index
;
4353 CSTAT(free_ip_address
);
4356 return; // what the?
4358 if (i
< 0) // Is this actually part of the ip pool?
4362 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4364 ip_address_pool
[i
].assigned
= 0;
4365 ip_address_pool
[i
].session
= 0;
4366 ip_address_pool
[i
].last
= time_now
;
4370 // Fsck the address pool against the session table.
4371 // Normally only called when we become a master.
4373 // This isn't perfect: We aren't keep tracking of which
4374 // users used to have an IP address.
4376 void rebuild_address_pool(void)
4381 // Zero the IP pool allocation, and build
4382 // a map from IP address to pool index.
4383 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4385 ip_address_pool
[i
].assigned
= 0;
4386 ip_address_pool
[i
].session
= 0;
4387 if (!ip_address_pool
[i
].address
)
4390 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4393 for (i
= 0; i
< MAXSESSION
; ++i
)
4396 if (!(session
[i
].opened
&& session
[i
].ip
))
4399 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4401 if (session
[i
].ip_pool_index
< 0)
4403 // Not allocated out of the pool.
4404 if (ipid
< 1) // Not found in the pool either? good.
4407 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4408 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4410 // Fall through and process it as part of the pool.
4414 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4416 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4418 session
[i
].ip_pool_index
= ipid
;
4422 ip_address_pool
[ipid
].assigned
= 1;
4423 ip_address_pool
[ipid
].session
= i
;
4424 ip_address_pool
[ipid
].last
= time_now
;
4425 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4426 session
[i
].ip_pool_index
= ipid
;
4427 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4432 // Fix the address pool to match a changed session.
4433 // (usually when the master sends us an update).
4434 static void fix_address_pool(int sid
)
4438 ipid
= session
[sid
].ip_pool_index
;
4440 if (ipid
> ip_pool_size
)
4441 return; // Ignore it. rebuild_address_pool will fix it up.
4443 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4444 return; // Just ignore it. rebuild_address_pool will take care of it.
4446 ip_address_pool
[ipid
].assigned
= 1;
4447 ip_address_pool
[ipid
].session
= sid
;
4448 ip_address_pool
[ipid
].last
= time_now
;
4449 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4453 // Add a block of addresses to the IP pool to hand out.
4455 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4459 prefixlen
= 32; // Host route only.
4461 addr
&= 0xffffffff << (32 - prefixlen
);
4463 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4466 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4468 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4469 continue; // Skip 0 and broadcast addresses.
4471 ip_address_pool
[ip_pool_size
].address
= i
;
4472 ip_address_pool
[ip_pool_size
].assigned
= 0;
4474 if (ip_pool_size
>= MAXIPPOOL
)
4476 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4482 // Initialize the IP address pool
4483 static void initippool()
4488 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4490 if (!(f
= fopen(IPPOOLFILE
, "r")))
4492 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4496 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4499 buf
[4095] = 0; // Force it to be zero terminated/
4501 if (*buf
== '#' || *buf
== '\n')
4502 continue; // Skip comments / blank lines
4503 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4504 if ((p
= (char *)strchr(buf
, ':')))
4508 src
= inet_addr(buf
);
4509 if (src
== INADDR_NONE
)
4511 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4514 // This entry is for a specific IP only
4515 if (src
!= config
->bind_address
)
4520 if ((p
= (char *)strchr(pool
, '/')))
4524 in_addr_t start
= 0;
4526 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4528 if (!*p
|| !(numbits
= atoi(p
)))
4530 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4533 start
= ntohl(inet_addr(pool
));
4535 // Add a static route for this pool
4536 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4537 fmtaddr(htonl(start
), 0), numbits
);
4539 routeset(0, start
, numbits
, 0, 1);
4541 add_to_ip_pool(start
, numbits
);
4545 // It's a single ip address
4546 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4550 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4553 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4555 struct sockaddr_in snoop_addr
= {0};
4556 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4559 snoop_addr
.sin_family
= AF_INET
;
4560 snoop_addr
.sin_addr
.s_addr
= destination
;
4561 snoop_addr
.sin_port
= ntohs(port
);
4563 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4564 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4565 htons(snoop_addr
.sin_port
));
4567 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4568 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4570 STAT(packets_snooped
);
4573 static int dump_session(FILE **f
, sessiont
*s
)
4575 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4580 char filename
[1024];
4582 time_t now
= time(NULL
);
4584 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4585 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4587 if (!(*f
= fopen(filename
, "w")))
4589 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4593 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4594 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4599 "# format: username ip qos uptxoctets downrxoctets\n",
4601 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4606 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4607 fprintf(*f
, "%s %s %d %u %u\n",
4608 s
->user
, // username
4609 fmtaddr(htonl(s
->ip
), 0), // ip
4610 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4611 (uint32_t) s
->cin_delta
, // uptxoctets
4612 (uint32_t) s
->cout_delta
); // downrxoctets
4614 s
->cin_delta
= s
->cout_delta
= 0;
4619 static void dump_acct_info(int all
)
4625 CSTAT(dump_acct_info
);
4629 for (i
= 0; i
< shut_acct_n
; i
++)
4630 dump_session(&f
, &shut_acct
[i
]);
4636 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4637 dump_session(&f
, &session
[i
]);
4644 int main(int argc
, char *argv
[])
4648 char *optconfig
= CONFIGFILE
;
4650 time(&basetime
); // start clock
4653 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4658 if (fork()) exit(0);
4660 freopen("/dev/null", "r", stdin
);
4661 freopen("/dev/null", "w", stdout
);
4662 freopen("/dev/null", "w", stderr
);
4671 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4674 printf("Args are:\n"
4675 "\t-d\t\tDetach from terminal\n"
4676 "\t-c <file>\tConfig file\n"
4677 "\t-h <hostname>\tForce hostname\n"
4685 // Start the timer routine off
4687 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4690 initdata(optdebug
, optconfig
);
4695 init_tbf(config
->num_tbfs
);
4697 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4698 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4699 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4702 rlim
.rlim_cur
= RLIM_INFINITY
;
4703 rlim
.rlim_max
= RLIM_INFINITY
;
4704 // Remove the maximum core size
4705 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4706 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4708 // Make core dumps go to /tmp
4712 if (config
->scheduler_fifo
)
4715 struct sched_param params
= {0};
4716 params
.sched_priority
= 1;
4718 if (get_nprocs() < 2)
4720 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4721 config
->scheduler_fifo
= 0;
4725 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4727 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4731 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4732 config
->scheduler_fifo
= 0;
4739 /* Set up the cluster communications port. */
4740 if (cluster_init() < 0)
4744 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4752 unsigned seed
= time_now
^ getpid();
4753 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4757 signal(SIGHUP
, sighup_handler
);
4758 signal(SIGCHLD
, sigchild_handler
);
4759 signal(SIGTERM
, shutdown_handler
);
4760 signal(SIGINT
, shutdown_handler
);
4761 signal(SIGQUIT
, shutdown_handler
);
4763 // Prevent us from getting paged out
4764 if (config
->lock_pages
)
4766 if (!mlockall(MCL_CURRENT
))
4767 LOG(1, 0, 0, "Locking pages into memory\n");
4769 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4774 /* remove plugins (so cleanup code gets run) */
4777 // Remove the PID file if we wrote it
4778 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4779 unlink(config
->pid_file
);
4781 /* kill CLI children */
4782 signal(SIGTERM
, SIG_IGN
);
4787 static void sighup_handler(int sig
)
4792 static void shutdown_handler(int sig
)
4794 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4797 static void sigchild_handler(int sig
)
4799 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4803 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4806 *challenge_response
= NULL
;
4808 if (!*config
->l2tp_secret
)
4810 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4814 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4816 *challenge_response
= calloc(17, 1);
4819 MD5_Update(&ctx
, &id
, 1);
4820 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4821 MD5_Update(&ctx
, challenge
, challenge_length
);
4822 MD5_Final(*challenge_response
, &ctx
);
4827 static int facility_value(char *name
)
4830 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4832 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4833 return facilitynames
[i
].c_val
;
4838 static void update_config()
4842 static int timeout
= 0;
4843 static int interval
= 0;
4850 if (log_stream
!= stderr
)
4856 if (*config
->log_filename
)
4858 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4860 char *p
= config
->log_filename
+ 7;
4863 openlog("l2tpns", LOG_PID
, facility_value(p
));
4867 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4869 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4871 fseek(log_stream
, 0, SEEK_END
);
4872 setbuf(log_stream
, NULL
);
4876 log_stream
= stderr
;
4877 setbuf(log_stream
, NULL
);
4883 log_stream
= stderr
;
4884 setbuf(log_stream
, NULL
);
4887 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4888 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4890 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4891 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4892 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4894 // reset MRU/MSS globals
4895 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4896 if (MRU
> PPPoE_MRU
)
4899 MSS
= MRU
- TCP_HDRS
;
4902 config
->numradiusservers
= 0;
4903 for (i
= 0; i
< MAXRADSERVER
; i
++)
4904 if (config
->radiusserver
[i
])
4906 config
->numradiusservers
++;
4907 // Set radius port: if not set, take the port from the
4908 // first radius server. For the first radius server,
4909 // take the #defined default value from l2tpns.h
4911 // test twice, In case someone works with
4912 // a secondary radius server without defining
4913 // a primary one, this will work even then.
4914 if (i
> 0 && !config
->radiusport
[i
])
4915 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4916 if (!config
->radiusport
[i
])
4917 config
->radiusport
[i
] = RADPORT
;
4920 if (!config
->numradiusservers
)
4921 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4923 // parse radius_authtypes_s
4924 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4925 p
= config
->radius_authtypes_s
;
4928 char *s
= strpbrk(p
, " \t,");
4934 while (*s
== ' ' || *s
== '\t')
4941 if (!strncasecmp("chap", p
, strlen(p
)))
4943 else if (!strncasecmp("pap", p
, strlen(p
)))
4946 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4948 config
->radius_authtypes
|= type
;
4949 if (!config
->radius_authprefer
)
4950 config
->radius_authprefer
= type
;
4955 if (!config
->radius_authtypes
)
4957 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4958 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4961 // normalise radius_authtypes_s
4962 if (config
->radius_authprefer
== AUTHPAP
)
4964 strcpy(config
->radius_authtypes_s
, "pap");
4965 if (config
->radius_authtypes
& AUTHCHAP
)
4966 strcat(config
->radius_authtypes_s
, ", chap");
4970 strcpy(config
->radius_authtypes_s
, "chap");
4971 if (config
->radius_authtypes
& AUTHPAP
)
4972 strcat(config
->radius_authtypes_s
, ", pap");
4975 if (!config
->radius_dae_port
)
4976 config
->radius_dae_port
= DAEPORT
;
4978 // re-initialise the random number source
4979 initrandom(config
->random_device
);
4982 for (i
= 0; i
< MAXPLUGINS
; i
++)
4984 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
4987 if (*config
->plugins
[i
])
4990 add_plugin(config
->plugins
[i
]);
4992 else if (*config
->old_plugins
[i
])
4995 remove_plugin(config
->old_plugins
[i
]);
5000 guest_accounts_num
= 0;
5001 char *p2
= config
->guest_user
;
5004 char *s
= strpbrk(p2
, " \t,");
5008 while (*s
== ' ' || *s
== '\t')
5015 strcpy(guest_users
[guest_accounts_num
], p2
);
5016 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5017 guest_accounts_num
++;
5020 // Rebuild the guest_user array
5021 strcpy(config
->guest_user
, "");
5023 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5025 strcat(config
->guest_user
, guest_users
[ui
]);
5026 if (ui
<guest_accounts_num
-1)
5028 strcat(config
->guest_user
, ",");
5033 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5034 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5035 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5036 if (!*config
->cluster_interface
)
5037 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5039 if (!config
->cluster_hb_interval
)
5040 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5042 if (!config
->cluster_hb_timeout
)
5043 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5045 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5047 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5048 // late, ensure we're sufficiently larger than that
5049 int t
= 4 * config
->cluster_hb_interval
+ 11;
5051 if (config
->cluster_hb_timeout
< t
)
5053 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5054 config
->cluster_hb_timeout
= t
;
5057 // Push timing changes to the slaves immediately if we're the master
5058 if (config
->cluster_iam_master
)
5059 cluster_heartbeat();
5061 interval
= config
->cluster_hb_interval
;
5062 timeout
= config
->cluster_hb_timeout
;
5066 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5069 if ((f
= fopen(config
->pid_file
, "w")))
5071 fprintf(f
, "%d\n", getpid());
5073 config
->wrote_pid
= 1;
5077 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5082 static void read_config_file()
5086 if (!config
->config_file
) return;
5087 if (!(f
= fopen(config
->config_file
, "r")))
5089 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5093 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5095 LOG(3, 0, 0, "Done reading config file\n");
5099 int sessionsetup(sessionidt s
, tunnelidt t
)
5101 // A session now exists, set it up
5107 CSTAT(sessionsetup
);
5109 LOG(3, s
, t
, "Doing session setup for session\n");
5111 // Join a bundle if the MRRU option is accepted
5112 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5114 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5115 if (join_bundle(s
) > 0)
5116 cluster_send_bundle(session
[s
].bundle
);
5119 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5120 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5127 assign_ip_address(s
);
5130 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5131 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5134 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5135 fmtaddr(htonl(session
[s
].ip
), 0));
5139 // Make sure this is right
5140 session
[s
].tunnel
= t
;
5142 // zap old sessions with same IP and/or username
5143 // Don't kill gardened sessions - doing so leads to a DoS
5144 // from someone who doesn't need to know the password
5147 user
= session
[s
].user
;
5148 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5150 if (i
== s
) continue;
5151 if (!session
[s
].opened
) continue;
5152 // Allow duplicate sessions for multilink ones of the same bundle.
5153 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5155 if (ip
== session
[i
].ip
)
5157 sessionkill(i
, "Duplicate IP address");
5161 if (config
->allow_duplicate_users
) continue;
5162 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5166 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5168 if (!strcasecmp(user
, guest_users
[gu
]))
5174 if (found
) continue;
5176 // Drop the new session in case of duplicate sessionss, not the old one.
5177 if (!strcasecmp(user
, session
[i
].user
))
5178 sessionkill(i
, "Duplicate session for users");
5182 // no need to set a route for the same IP address of the bundle
5183 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5187 // Add the route for this session.
5188 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5190 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5191 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5194 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5197 // Static IPs need to be routed if not already
5198 // convered by a Framed-Route. Anything else is part
5199 // of the IP address pool and is already routed, it
5200 // just needs to be added to the IP cache.
5201 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5202 if (session
[s
].ip_pool_index
== -1) // static ip
5204 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5207 cache_ipmap(session
[s
].ip
, s
);
5210 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5211 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5213 // Run the plugin's against this new session.
5215 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5216 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5219 // Allocate TBFs if throttled
5220 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5221 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5223 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5225 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5226 fmtaddr(htonl(session
[s
].ip
), 0),
5227 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5229 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5231 return 1; // RADIUS OK and IP allocated, done...
5235 // This session just got dropped on us by the master or something.
5236 // Make sure our tables up up to date...
5238 int load_session(sessionidt s
, sessiont
*new)
5244 if (new->ip_pool_index
>= MAXIPPOOL
||
5245 new->tunnel
>= MAXTUNNEL
)
5247 LOG(0, s
, 0, "Strange session update received!\n");
5248 // FIXME! What to do here?
5253 // Ok. All sanity checks passed. Now we're committed to
5254 // loading the new session.
5257 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5259 // See if routes/ip cache need updating
5260 if (new->ip
!= session
[s
].ip
)
5263 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5264 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5265 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5273 // remove old routes...
5274 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5276 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5277 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5280 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5286 if (session
[s
].ip_pool_index
== -1) // static IP
5288 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5290 else // It's part of the IP pool, remove it manually.
5291 uncache_ipmap(session
[s
].ip
);
5296 // add new routes...
5297 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5299 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5300 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5303 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5309 // If there's a new one, add it.
5310 if (new->ip_pool_index
== -1)
5312 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5315 cache_ipmap(new->ip
, s
);
5320 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5321 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5324 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5326 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5330 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5332 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5333 new->filter_out
= 0;
5336 if (new->filter_in
!= session
[s
].filter_in
)
5338 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5339 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5342 if (new->filter_out
!= session
[s
].filter_out
)
5344 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5345 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5348 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5349 // for walking the sessions to forward byte counts to the master.
5350 config
->cluster_highest_sessionid
= s
;
5352 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5354 // Do fixups into address pool.
5355 if (new->ip_pool_index
!= -1)
5356 fix_address_pool(s
);
5361 static void initplugins()
5365 loaded_plugins
= ll_init();
5366 // Initialize the plugins to nothing
5367 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5368 plugins
[i
] = ll_init();
5371 static void *open_plugin(char *plugin_name
, int load
)
5373 char path
[256] = "";
5375 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5376 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5377 return dlopen(path
, RTLD_NOW
);
5380 // plugin callback to get a config value
5381 static void *getconfig(char *key
, enum config_typet type
)
5385 for (i
= 0; config_values
[i
].key
; i
++)
5387 if (!strcmp(config_values
[i
].key
, key
))
5389 if (config_values
[i
].type
== type
)
5390 return ((void *) config
) + config_values
[i
].offset
;
5392 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5393 key
, type
, config_values
[i
].type
);
5399 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5403 static int add_plugin(char *plugin_name
)
5405 static struct pluginfuncs funcs
= {
5410 sessiontbysessionidt
,
5411 sessionidtbysessiont
,
5418 cluster_send_session
,
5421 void *p
= open_plugin(plugin_name
, 1);
5422 int (*initfunc
)(struct pluginfuncs
*);
5427 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5431 if (ll_contains(loaded_plugins
, p
))
5434 return 0; // already loaded
5438 int *v
= dlsym(p
, "plugin_api_version");
5439 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5441 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5447 if ((initfunc
= dlsym(p
, "plugin_init")))
5449 if (!initfunc(&funcs
))
5451 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5457 ll_push(loaded_plugins
, p
);
5459 for (i
= 0; i
< max_plugin_functions
; i
++)
5462 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5464 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5465 ll_push(plugins
[i
], x
);
5469 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5473 static void run_plugin_done(void *plugin
)
5475 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5481 static int remove_plugin(char *plugin_name
)
5483 void *p
= open_plugin(plugin_name
, 0);
5489 if (ll_contains(loaded_plugins
, p
))
5492 for (i
= 0; i
< max_plugin_functions
; i
++)
5495 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5496 ll_delete(plugins
[i
], x
);
5499 ll_delete(loaded_plugins
, p
);
5505 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5509 int run_plugins(int plugin_type
, void *data
)
5511 int (*func
)(void *data
);
5513 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5514 return PLUGIN_RET_ERROR
;
5516 ll_reset(plugins
[plugin_type
]);
5517 while ((func
= ll_next(plugins
[plugin_type
])))
5521 if (r
!= PLUGIN_RET_OK
)
5522 return r
; // stop here
5525 return PLUGIN_RET_OK
;
5528 static void plugins_done()
5532 ll_reset(loaded_plugins
);
5533 while ((p
= ll_next(loaded_plugins
)))
5537 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5539 struct nsctl request
;
5540 struct nsctl response
;
5541 int type
= unpack_control(&request
, buf
, len
);
5545 if (log_stream
&& config
->debug
>= 4)
5549 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5550 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5554 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5555 dump_control(&request
, log_stream
);
5561 case NSCTL_REQ_LOAD
:
5562 if (request
.argc
!= 1)
5564 response
.type
= NSCTL_RES_ERR
;
5566 response
.argv
[0] = "name of plugin required";
5568 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5570 response
.type
= NSCTL_RES_ERR
;
5572 response
.argv
[0] = !r
5573 ? "plugin already loaded"
5574 : "error loading plugin";
5578 response
.type
= NSCTL_RES_OK
;
5584 case NSCTL_REQ_UNLOAD
:
5585 if (request
.argc
!= 1)
5587 response
.type
= NSCTL_RES_ERR
;
5589 response
.argv
[0] = "name of plugin required";
5591 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5593 response
.type
= NSCTL_RES_ERR
;
5595 response
.argv
[0] = !r
5596 ? "plugin not loaded"
5597 : "plugin not found";
5601 response
.type
= NSCTL_RES_OK
;
5607 case NSCTL_REQ_HELP
:
5608 response
.type
= NSCTL_RES_OK
;
5611 ll_reset(loaded_plugins
);
5612 while ((p
= ll_next(loaded_plugins
)))
5614 char **help
= dlsym(p
, "plugin_control_help");
5615 while (response
.argc
< 0xff && help
&& *help
)
5616 response
.argv
[response
.argc
++] = *help
++;
5621 case NSCTL_REQ_CONTROL
:
5623 struct param_control param
= {
5624 config
->cluster_iam_master
,
5631 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5633 if (r
== PLUGIN_RET_ERROR
)
5635 response
.type
= NSCTL_RES_ERR
;
5637 response
.argv
[0] = param
.additional
5639 : "error returned by plugin";
5641 else if (r
== PLUGIN_RET_NOTMASTER
)
5643 static char msg
[] = "must be run on master: 000.000.000.000";
5645 response
.type
= NSCTL_RES_ERR
;
5647 if (config
->cluster_master_address
)
5649 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5650 response
.argv
[0] = msg
;
5654 response
.argv
[0] = "must be run on master: none elected";
5657 else if (!(param
.response
& NSCTL_RESPONSE
))
5659 response
.type
= NSCTL_RES_ERR
;
5661 response
.argv
[0] = param
.response
5662 ? "unrecognised response value from plugin"
5663 : "unhandled action";
5667 response
.type
= param
.response
;
5669 if (param
.additional
)
5672 response
.argv
[0] = param
.additional
;
5680 response
.type
= NSCTL_RES_ERR
;
5682 response
.argv
[0] = "error unpacking control packet";
5685 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5688 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5692 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5695 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5696 if (log_stream
&& config
->debug
>= 4)
5698 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5699 dump_control(&response
, log_stream
);
5703 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5704 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5709 static tunnelidt
new_tunnel()
5712 for (i
= 1; i
< MAXTUNNEL
; i
++)
5714 if (tunnel
[i
].state
== TUNNELFREE
)
5716 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5717 if (i
> config
->cluster_highest_tunnelid
)
5718 config
->cluster_highest_tunnelid
= i
;
5722 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5727 // We're becoming the master. Do any required setup..
5729 // This is principally telling all the plugins that we're
5730 // now a master, and telling them about all the sessions
5731 // that are active too..
5733 void become_master(void)
5736 static struct event_data d
[RADIUS_FDS
];
5737 struct epoll_event e
;
5739 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5741 // running a bunch of iptables commands is slow and can cause
5742 // the master to drop tunnels on takeover--kludge around the
5743 // problem by forking for the moment (note: race)
5744 if (!fork_and_close())
5746 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5748 if (!session
[s
].opened
) // Not an in-use session.
5751 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5758 for (i
= 0; i
< RADIUS_FDS
; i
++)
5760 d
[i
].type
= FD_TYPE_RADIUS
;
5764 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5768 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5774 if (CLI_HELP_REQUESTED
)
5775 return CLI_HELP_NO_ARGS
;
5778 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5780 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5783 if (!session
[s
].opened
)
5786 idle
= time_now
- session
[s
].last_data
;
5787 idle
/= 5 ; // In multiples of 5 seconds.
5797 for (i
= 0; i
< 63; ++i
)
5799 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5801 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5802 cli_print(cli
, "%d total sessions open.", count
);
5806 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5812 if (CLI_HELP_REQUESTED
)
5813 return CLI_HELP_NO_ARGS
;
5816 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5818 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5821 if (!session
[s
].opened
)
5824 d
= time_now
- session
[s
].opened
;
5827 while (d
> 1 && open
< 32)
5837 for (i
= 0; i
< 30; ++i
)
5839 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5842 cli_print(cli
, "%d total sessions open.", count
);
5848 * This unencodes the AVP using the L2TP secret and the previously
5849 * stored random vector. It overwrites the hidden data with the
5850 * unhidden AVP subformat.
5852 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5858 uint16_t m
= htons(type
);
5860 // Compute initial pad
5862 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5863 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5864 MD5_Update(&ctx
, vector
, vec_len
);
5865 MD5_Final(digest
, &ctx
);
5867 // pointer to last decoded 16 octets
5872 // calculate a new pad based on the last decoded block
5873 if (d
>= sizeof(digest
))
5876 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5877 MD5_Update(&ctx
, last
, sizeof(digest
));
5878 MD5_Final(digest
, &ctx
);
5884 *value
++ ^= digest
[d
++];
5889 int find_filter(char const *name
, size_t len
)
5894 for (i
= 0; i
< MAXFILTER
; i
++)
5896 if (!*ip_filters
[i
].name
)
5904 if (strlen(ip_filters
[i
].name
) != len
)
5907 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5914 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5918 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5919 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5920 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5921 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5922 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5928 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5932 case FILTER_FLAG_OP_ANY
:
5933 return (flags
& sflags
) || (~flags
& cflags
);
5935 case FILTER_FLAG_OP_ALL
:
5936 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5938 case FILTER_FLAG_OP_EST
:
5939 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5945 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5947 uint16_t frag_offset
;
5951 uint16_t src_port
= 0;
5952 uint16_t dst_port
= 0;
5954 ip_filter_rulet
*rule
;
5956 if (len
< 20) // up to end of destination address
5959 if ((*buf
>> 4) != 4) // IPv4
5962 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5964 src_ip
= *(in_addr_t
*) (buf
+ 12);
5965 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5967 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5969 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5970 if (len
< l
+ 4) // ports
5973 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
5974 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
5975 if (proto
== IPPROTO_TCP
)
5977 if (len
< l
+ 14) // flags
5980 flags
= buf
[l
+ 13] & 0x3f;
5984 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
5986 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
5989 if (rule
->src_wild
!= INADDR_BROADCAST
&&
5990 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
5993 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
5994 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
5999 // layer 4 deny rules are skipped
6000 if (rule
->action
== FILTER_ACTION_DENY
&&
6001 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6009 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6011 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6014 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6017 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6018 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6025 return rule
->action
== FILTER_ACTION_PERMIT
;