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)
644 struct ifinfomsg ifinfo
;
647 memset(&ifr
, 0, sizeof(ifr
));
648 ifr
.ifr_flags
= IFF_TUN
;
650 tunfd
= open(TUNDEVICE
, O_RDWR
);
653 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
657 int flags
= fcntl(tunfd
, F_GETFL
, 0);
658 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
660 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
662 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
665 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
) - 1);
666 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
));
669 // get the interface index
672 struct ifinfomsg ifinfo
;
676 struct nlmsghdr
*resp_nh
;
678 req
.nh
.nlmsg_type
= RTM_GETLINK
;
679 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
680 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifinfo
));
682 req
.ifinfo
.ifi_family
= AF_UNSPEC
; // as the man says
684 netlink_addattr(&req
.nh
, IFLA_IFNAME
, config
->tundevice
, strlen(config
->tundevice
)+1);
686 if(netlink_send(&req
.nh
) < 0 || (len
= netlink_recv(buf
, sizeof(buf
))) < 0)
688 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno
));
692 resp_nh
= (struct nlmsghdr
*)buf
;
693 if (!NLMSG_OK (resp_nh
, len
))
695 LOG(0, 0, 0, "Malformed answer getting tun ifindex %ld\n", len
);
699 memcpy(&ifinfo
, NLMSG_DATA(resp_nh
), sizeof(ifinfo
));
701 tunidx
= ifinfo
.ifi_index
;
708 struct ifinfomsg ifinfo
;
709 struct ifaddrmsg ifaddr
;
711 char rtdata
[32]; // 32 should be enough
713 uint32_t txqlen
, mtu
;
716 memset(&req
, 0, sizeof(req
));
718 req
.nh
.nlmsg_type
= RTM_SETLINK
;
719 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
720 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
722 req
.ifmsg
.ifinfo
= ifinfo
;
723 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
724 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
726 /* Bump up the qlen to deal with bursts from the network */
728 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
729 /* set MTU to modem MRU */
731 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
733 if (netlink_send(&req
.nh
) < 0)
736 memset(&req
, 0, sizeof(req
));
738 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
739 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_MULTI
;
740 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
742 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
743 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
744 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
746 if (config
->bind_address
)
747 ip
.s_addr
= config
->bind_address
;
749 ip
.s_addr
= 0x01010101, // 1.1.1.1
750 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
752 if (netlink_send(&req
.nh
) < 0)
755 // Only setup IPv6 on the tun device if we have a configured prefix
756 if (config
->ipv6_prefix
.s6_addr
[0]) {
759 memset(&req
, 0, sizeof(req
));
761 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
762 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_MULTI
;
763 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
765 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
766 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
767 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
768 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
770 // Link local address is FE80::1
771 memset(&ip6
, 0, sizeof(ip6
));
772 ip6
.s6_addr
[0] = 0xFE;
773 ip6
.s6_addr
[1] = 0x80;
775 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
777 if (netlink_send(&req
.nh
) < 0)
780 memset(&req
, 0, sizeof(req
));
782 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
783 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_MULTI
;
784 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
786 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
787 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
788 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
789 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
791 // Global address is prefix::1
792 ip6
= config
->ipv6_prefix
;
794 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
796 if (netlink_send(&req
.nh
) < 0)
800 memset(&req
, 0, sizeof(req
));
802 req
.nh
.nlmsg_type
= NLMSG_DONE
;
803 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
805 if (netlink_send(&req
.nh
) < 0)
808 // if we get an error for seqnum < min_initok_nlseqnum,
809 // we must exit as initialization went wrong
810 if (config
->ipv6_prefix
.s6_addr
[0])
811 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
813 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
819 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
824 static void initudp(void)
827 struct sockaddr_in addr
;
830 memset(&addr
, 0, sizeof(addr
));
831 addr
.sin_family
= AF_INET
;
832 addr
.sin_port
= htons(L2TPPORT
);
833 addr
.sin_addr
.s_addr
= config
->bind_address
;
834 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
835 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
837 int flags
= fcntl(udpfd
, F_GETFL
, 0);
838 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
840 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
842 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
847 memset(&addr
, 0, sizeof(addr
));
848 addr
.sin_family
= AF_INET
;
849 addr
.sin_port
= htons(NSCTL_PORT
);
850 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
851 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
852 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
853 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
855 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
859 // Dynamic Authorization Extensions to RADIUS
860 memset(&addr
, 0, sizeof(addr
));
861 addr
.sin_family
= AF_INET
;
862 addr
.sin_port
= htons(config
->radius_dae_port
);
863 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
864 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
865 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
866 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
868 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
873 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
877 // Find session by IP, < 1 for not found
879 // Confusingly enough, this 'ip' must be
880 // in _network_ order. This being the common
881 // case when looking it up from IP packet headers.
883 // We actually use this cache for two things.
884 // #1. For used IP addresses, this maps to the
885 // session ID that it's used by.
886 // #2. For un-used IP addresses, this maps to the
887 // index into the pool table that contains that
891 static sessionidt
lookup_ipmap(in_addr_t ip
)
893 uint8_t *a
= (uint8_t *) &ip
;
894 union iphash
*h
= ip_hash
;
896 if (!(h
= h
[*a
++].idx
)) return 0;
897 if (!(h
= h
[*a
++].idx
)) return 0;
898 if (!(h
= h
[*a
++].idx
)) return 0;
903 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
905 struct ipv6radix
*curnode
;
908 char ipv6addr
[INET6_ADDRSTRLEN
];
910 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
914 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
916 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
921 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
922 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
929 sessionidt
sessionbyip(in_addr_t ip
)
931 sessionidt s
= lookup_ipmap(ip
);
934 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
940 sessionidt
sessionbyipv6(struct in6_addr ip
)
943 CSTAT(sessionbyipv6
);
945 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
946 (ip
.s6_addr
[0] == 0xFE &&
947 ip
.s6_addr
[1] == 0x80 &&
948 ip
.s6_addr16
[1] == 0 &&
949 ip
.s6_addr16
[2] == 0 &&
950 ip
.s6_addr16
[3] == 0)) {
951 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
953 s
= lookup_ipv6map(ip
);
956 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
963 // Take an IP address in HOST byte order and
964 // add it to the sessionid by IP cache.
966 // (It's actually cached in network order)
968 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
970 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
971 uint8_t *a
= (uint8_t *) &nip
;
972 union iphash
*h
= ip_hash
;
975 for (i
= 0; i
< 3; i
++)
977 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
986 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
989 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
990 // else a map to an ip pool index.
993 static void uncache_ipmap(in_addr_t ip
)
995 cache_ipmap(ip
, 0); // Assign it to the NULL session.
998 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1002 struct ipv6radix
*curnode
;
1003 char ipv6addr
[INET6_ADDRSTRLEN
];
1005 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
1007 bytes
= prefixlen
>> 3;
1010 if (curnode
->branch
== NULL
)
1012 if (!(curnode
->branch
= calloc(256,
1013 sizeof (struct ipv6radix
))))
1016 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1023 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1024 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1028 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1029 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1035 // CLI list to dump current ipcache.
1037 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1039 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1043 if (CLI_HELP_REQUESTED
)
1044 return CLI_HELP_NO_ARGS
;
1046 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1048 for (i
= 0; i
< 256; ++i
)
1054 for (j
= 0; j
< 256; ++j
)
1060 for (k
= 0; k
< 256; ++k
)
1066 for (l
= 0; l
< 256; ++l
)
1071 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1077 cli_print(cli
, "%d entries in cache", count
);
1082 // Find session by username, 0 for not found
1083 // walled garden users aren't authenticated, so the username is
1084 // reasonably useless. Ignore them to avoid incorrect actions
1086 // This is VERY inefficent. Don't call it often. :)
1088 sessionidt
sessionbyuser(char *username
)
1091 CSTAT(sessionbyuser
);
1093 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1095 if (!session
[s
].opened
)
1098 if (session
[s
].walled_garden
)
1099 continue; // Skip walled garden users.
1101 if (!strncmp(session
[s
].user
, username
, 128))
1105 return 0; // Not found.
1108 void send_garp(in_addr_t ip
)
1114 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1117 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1120 memset(&ifr
, 0, sizeof(ifr
));
1121 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1122 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1124 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1128 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1129 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1131 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1136 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1139 static sessiont
*sessiontbysessionidt(sessionidt s
)
1141 if (!s
|| s
>= MAXSESSION
) return NULL
;
1145 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1147 sessionidt val
= s
-session
;
1148 if (s
< session
|| val
>= MAXSESSION
) return 0;
1152 // actually send a control message for a specific tunnel
1153 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1155 struct sockaddr_in addr
;
1161 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1162 STAT(tunnel_tx_errors
);
1168 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1169 STAT(tunnel_tx_errors
);
1173 memset(&addr
, 0, sizeof(addr
));
1174 addr
.sin_family
= AF_INET
;
1175 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1176 addr
.sin_port
= htons(tunnel
[t
].port
);
1178 // sequence expected, if sequence in message
1179 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1181 // If this is a control message, deal with retries
1184 tunnel
[t
].last
= time_now
; // control message sent
1185 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1188 STAT(tunnel_retries
);
1189 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1193 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1195 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1196 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1197 STAT(tunnel_tx_errors
);
1201 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1202 STAT(tunnel_tx_packets
);
1203 INC_STAT(tunnel_tx_bytes
, l
);
1207 // Tiny helper function to write data to
1208 // the 'tun' device.
1210 int tun_write(uint8_t * data
, int size
)
1212 return write(tunfd
, data
, size
);
1215 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1216 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1218 int d
= (tcp
[12] >> 4) * 4;
1225 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1228 if (tcp
+ d
> buf
+ len
) // short?
1236 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1239 if (mss
+ 2 > data
) return; // short?
1243 if (*opts
== 0) return; // end of options
1244 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1247 opts
+= opts
[1]; // skip over option
1250 if (!mss
) return; // not found
1251 orig
= ntohs(*(uint16_t *) mss
);
1253 if (orig
<= MSS
) return; // mss OK
1255 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1256 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1257 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1258 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1261 *(int16_t *) mss
= htons(MSS
);
1263 // adjust checksum (see rfc1141)
1264 sum
= orig
+ (~MSS
& 0xffff);
1265 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1266 sum
= (sum
& 0xffff) + (sum
>> 16);
1267 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1270 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1274 // Skip the four extra bytes
1286 proto
= ntohs(*(uint16_t *) p
);
1294 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1295 return; // closing session, PPP not processed
1297 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1298 processipin(s
, t
, p
, l
);
1300 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1304 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1305 return; // closing session, PPP not processed
1308 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1309 processipv6in(s
, t
, p
, l
);
1311 else if (proto
== PPPIPCP
)
1313 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1314 processipcp(s
, t
, p
, l
);
1316 else if (proto
== PPPCCP
)
1318 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1319 processccp(s
, t
, p
, l
);
1323 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1327 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1329 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1330 sp
->cout_delta
+= len
;
1332 sp
->last_data
= time_now
;
1334 sess_local
[s
].cout
+= len
; // To send to master..
1335 sess_local
[s
].pout
++;
1338 // process outgoing (to tunnel) IP
1340 static void processipout(uint8_t *buf
, int len
)
1347 uint8_t *data
= buf
; // Keep a copy of the originals.
1350 uint8_t fragbuf
[MAXETHER
+ 20];
1352 CSTAT(processipout
);
1354 if (len
< MIN_IP_SIZE
)
1356 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1357 STAT(tun_rx_errors
);
1360 if (len
>= MAXETHER
)
1362 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1363 STAT(tun_rx_errors
);
1367 // Skip the tun header
1371 // Got an IP header now
1372 if (*(uint8_t *)(buf
) >> 4 != 4)
1374 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1378 ip
= *(uint32_t *)(buf
+ 16);
1379 if (!(s
= sessionbyip(ip
)))
1381 // Is this a packet for a session that doesn't exist?
1382 static int rate
= 0; // Number of ICMP packets we've sent this second.
1383 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1385 if (last
!= time_now
)
1391 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1393 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1394 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1395 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1400 t
= session
[s
].tunnel
;
1401 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1403 LOG(3, s
, t
, "Packet size more than session MRU\n");
1409 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1410 if (config
->max_packets
> 0)
1412 if (sess_local
[s
].last_packet_out
== TIME
)
1414 int max
= config
->max_packets
;
1416 // All packets for throttled sessions are handled by the
1417 // master, so further limit by using the throttle rate.
1418 // A bit of a kludge, since throttle rate is in kbps,
1419 // but should still be generous given our average DSL
1420 // packet size is 200 bytes: a limit of 28kbps equates
1421 // to around 180 packets per second.
1422 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1423 max
= sp
->throttle_out
;
1425 if (++sess_local
[s
].packets_out
> max
)
1427 sess_local
[s
].packets_dropped
++;
1433 if (sess_local
[s
].packets_dropped
)
1435 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1436 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1437 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1438 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1442 sess_local
[s
].last_packet_out
= TIME
;
1443 sess_local
[s
].packets_out
= 1;
1444 sess_local
[s
].packets_dropped
= 0;
1448 // run access-list if any
1449 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1452 // adjust MSS on SYN and SYN,ACK packets with options
1453 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1455 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1456 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1457 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1462 // Are we throttling this session?
1463 if (config
->cluster_iam_master
)
1464 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1466 master_throttle_packet(sp
->tbf_out
, data
, size
);
1470 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1472 // We are walled-gardening this
1473 master_garden_packet(s
, data
, size
);
1477 // Add on L2TP header
1480 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1482 bid
= session
[s
].bundle
;
1483 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1484 t
= session
[s
].tunnel
;
1486 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1487 if(len
> MINFRAGLEN
)
1489 // Partition the packet to "bundle[b].num_of_links" fragments
1490 bundlet
*b
= &bundle
[bid
];
1491 uint32_t num_of_links
= b
->num_of_links
;
1492 uint32_t fraglen
= len
/ num_of_links
;
1493 fraglen
= (fraglen
> session
[s
].mru
? session
[s
].mru
: fraglen
);
1494 uint32_t last_fraglen
= fraglen
+ len
% num_of_links
;
1495 last_fraglen
= (last_fraglen
> session
[s
].mru
? len
% num_of_links
: last_fraglen
);
1496 uint32_t remain
= len
;
1498 // send the first packet
1499 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1501 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1503 update_session_out_stat(s
, sp
, fraglen
);
1505 while (remain
> last_fraglen
)
1507 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1508 t
= session
[s
].tunnel
;
1510 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1511 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1513 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1514 update_session_out_stat(s
, sp
, fraglen
);
1517 // send the last fragment
1518 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1519 t
= session
[s
].tunnel
;
1521 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1522 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1524 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1525 update_session_out_stat(s
, sp
, remain
);
1526 if (remain
!= last_fraglen
)
1527 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1530 // Send it as one frame
1531 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1533 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1534 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1535 update_session_out_stat(s
, sp
, len
);
1540 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1542 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1543 update_session_out_stat(s
, sp
, len
);
1547 // Snooping this session, send it to intercept box
1548 if (sp
->snoop_ip
&& sp
->snoop_port
)
1549 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1554 // process outgoing (to tunnel) IPv6
1556 static void processipv6out(uint8_t * buf
, int len
)
1562 struct in6_addr ip6
;
1564 uint8_t *data
= buf
; // Keep a copy of the originals.
1567 uint8_t b
[MAXETHER
+ 20];
1569 CSTAT(processipv6out
);
1571 if (len
< MIN_IP_SIZE
)
1573 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1574 STAT(tunnel_tx_errors
);
1577 if (len
>= MAXETHER
)
1579 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1580 STAT(tunnel_tx_errors
);
1584 // Skip the tun header
1588 // Got an IP header now
1589 if (*(uint8_t *)(buf
) >> 4 != 6)
1591 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1595 ip6
= *(struct in6_addr
*)(buf
+24);
1596 s
= sessionbyipv6(ip6
);
1600 ip
= *(uint32_t *)(buf
+ 32);
1601 s
= sessionbyip(ip
);
1606 // Is this a packet for a session that doesn't exist?
1607 static int rate
= 0; // Number of ICMP packets we've sent this second.
1608 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1610 if (last
!= time_now
)
1616 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1618 // FIXME: Should send icmp6 host unreachable
1622 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1624 bundleidt bid
= session
[s
].bundle
;
1625 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1626 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1628 t
= session
[s
].tunnel
;
1630 sp
->last_data
= time_now
;
1632 // FIXME: add DoS prevention/filters?
1636 // Are we throttling this session?
1637 if (config
->cluster_iam_master
)
1638 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1640 master_throttle_packet(sp
->tbf_out
, data
, size
);
1643 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1645 // We are walled-gardening this
1646 master_garden_packet(s
, data
, size
);
1650 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1652 // Add on L2TP header
1654 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1656 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1659 // Snooping this session, send it to intercept box
1660 if (sp
->snoop_ip
&& sp
->snoop_port
)
1661 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1663 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1664 sp
->cout_delta
+= len
;
1668 sess_local
[s
].cout
+= len
; // To send to master..
1669 sess_local
[s
].pout
++;
1673 // Helper routine for the TBF filters.
1674 // Used to send queued data in to the user!
1676 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1682 uint8_t b
[MAXETHER
+ 20];
1684 if (len
< 0 || len
> MAXETHER
)
1686 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1690 // Skip the tun header
1694 ip
= *(in_addr_t
*)(buf
+ 16);
1699 t
= session
[s
].tunnel
;
1702 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1704 // Add on L2TP header
1706 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1708 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1711 // Snooping this session.
1712 if (sp
->snoop_ip
&& sp
->snoop_port
)
1713 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1715 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1716 sp
->cout_delta
+= len
;
1720 sess_local
[s
].cout
+= len
; // To send to master..
1721 sess_local
[s
].pout
++;
1724 // add an AVP (16 bit)
1725 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1727 uint16_t l
= (m
? 0x8008 : 0x0008);
1728 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1729 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1730 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1731 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1735 // add an AVP (32 bit)
1736 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1738 uint16_t l
= (m
? 0x800A : 0x000A);
1739 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1740 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1741 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1742 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1746 // add an AVP (string)
1747 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1749 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1750 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1751 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1752 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1753 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1754 c
->length
+= 6 + strlen(val
);
1758 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1760 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1761 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1762 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1763 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1764 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1765 c
->length
+= 6 + len
;
1768 // new control connection
1769 static controlt
*controlnew(uint16_t mtype
)
1773 c
= malloc(sizeof(controlt
));
1777 controlfree
= c
->next
;
1781 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1783 control16(c
, 0, mtype
, 1);
1787 // send zero block if nothing is waiting
1789 static void controlnull(tunnelidt t
)
1792 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1795 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1796 *(uint16_t *) (buf
+ 2) = htons(12); // length
1797 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1798 *(uint16_t *) (buf
+ 6) = htons(0); // session
1799 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1800 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1801 tunnelsend(buf
, 12, t
);
1804 // add a control message to a tunnel, and send if within window
1805 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1807 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1808 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1809 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1810 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1811 tunnel
[t
].ns
++; // advance sequence
1812 // link in message in to queue
1813 if (tunnel
[t
].controlc
)
1814 tunnel
[t
].controle
->next
= c
;
1816 tunnel
[t
].controls
= c
;
1818 tunnel
[t
].controle
= c
;
1819 tunnel
[t
].controlc
++;
1821 // send now if space in window
1822 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1824 tunnel
[t
].try = 0; // first send
1825 tunnelsend(c
->buf
, c
->length
, t
);
1830 // Throttle or Unthrottle a session
1832 // Throttle the data from/to through a session to no more than
1833 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1836 // If either value is -1, the current value is retained for that
1839 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1841 if (!session
[s
].opened
)
1842 return; // No-one home.
1844 if (!*session
[s
].user
)
1845 return; // User not logged in
1849 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1850 if (session
[s
].tbf_in
)
1851 free_tbf(session
[s
].tbf_in
);
1854 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1856 session
[s
].tbf_in
= 0;
1858 session
[s
].throttle_in
= rate_in
;
1863 int bytes
= rate_out
* 1024 / 8;
1864 if (session
[s
].tbf_out
)
1865 free_tbf(session
[s
].tbf_out
);
1868 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1870 session
[s
].tbf_out
= 0;
1872 session
[s
].throttle_out
= rate_out
;
1876 // add/remove filters from session (-1 = no change)
1877 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1879 if (!session
[s
].opened
)
1880 return; // No-one home.
1882 if (!*session
[s
].user
)
1883 return; // User not logged in
1886 if (filter_in
> MAXFILTER
) filter_in
= -1;
1887 if (filter_out
> MAXFILTER
) filter_out
= -1;
1888 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1889 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1893 if (session
[s
].filter_in
)
1894 ip_filters
[session
[s
].filter_in
- 1].used
--;
1897 ip_filters
[filter_in
- 1].used
++;
1899 session
[s
].filter_in
= filter_in
;
1902 if (filter_out
>= 0)
1904 if (session
[s
].filter_out
)
1905 ip_filters
[session
[s
].filter_out
- 1].used
--;
1908 ip_filters
[filter_out
- 1].used
++;
1910 session
[s
].filter_out
= filter_out
;
1914 // start tidy shutdown of session
1915 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1917 int walled_garden
= session
[s
].walled_garden
;
1918 bundleidt b
= session
[s
].bundle
;
1919 //delete routes only for last session in bundle (in case of MPPP)
1920 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1922 CSTAT(sessionshutdown
);
1924 if (!session
[s
].opened
)
1926 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1927 return; // not a live session
1930 if (!session
[s
].die
)
1932 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1933 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1934 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1935 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1938 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1940 // RADIUS Stop message
1941 uint16_t r
= radiusnew(s
);
1944 // stop, if not already trying
1945 if (radius
[r
].state
!= RADIUSSTOP
)
1947 radius
[r
].term_cause
= term_cause
;
1948 radius
[r
].term_msg
= reason
;
1949 radiussend(r
, RADIUSSTOP
);
1953 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1955 // Save counters to dump to accounting file
1956 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1957 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1961 { // IP allocated, clear and unroute
1964 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1966 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
1967 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
1970 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
1971 session
[s
].route
[r
].ip
= 0;
1974 if (session
[s
].ip_pool_index
== -1) // static ip
1976 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1982 // unroute IPv6, if setup
1983 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
1984 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1988 // This session was part of a bundle
1989 bundle
[b
].num_of_links
--;
1990 LOG(3, s
, 0, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
1991 if(bundle
[b
].num_of_links
== 0)
1994 LOG(3, s
, 0, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
1998 // Adjust the members array to accomodate the new change
1999 uint8_t mem_num
= 0;
2000 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2001 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2004 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2005 if(bundle
[b
].members
[ml
] == s
)
2010 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2011 LOG(3, s
, 0, "MPPP: Adjusted member links array\n");
2014 cluster_send_bundle(b
);
2018 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2019 throttle_session(s
, 0, 0);
2023 controlt
*c
= controlnew(14); // sending CDN
2027 *(uint16_t *) buf
= htons(cdn_result
);
2028 *(uint16_t *) (buf
+2) = htons(cdn_error
);
2029 controlb(c
, 1, buf
, 4, 1);
2032 control16(c
, 1, cdn_result
, 1);
2034 control16(c
, 14, s
, 1); // assigned session (our end)
2035 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2038 // update filter refcounts
2039 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2040 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2043 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2044 sess_local
[s
].lcp
.restart
= 0;
2045 sess_local
[s
].ipcp
.restart
= 0;
2046 sess_local
[s
].ipv6cp
.restart
= 0;
2047 sess_local
[s
].ccp
.restart
= 0;
2049 cluster_send_session(s
);
2052 void sendipcp(sessionidt s
, tunnelidt t
)
2054 uint8_t buf
[MAXETHER
];
2058 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2060 if (!session
[s
].unique_id
)
2062 if (!++last_id
) ++last_id
; // skip zero
2063 session
[s
].unique_id
= last_id
;
2066 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2070 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2071 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2072 q
[4] = 3; // ip address option
2073 q
[5] = 6; // option length
2074 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2075 config
->bind_address
? config
->bind_address
:
2076 my_address
; // send my IP
2078 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2079 restart_timer(s
, ipcp
);
2082 void sendipv6cp(sessionidt s
, tunnelidt t
)
2084 uint8_t buf
[MAXETHER
];
2088 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2090 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2094 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2095 // only send one type
2097 *(uint16_t *) (q
+ 2) = htons(14);
2098 q
[4] = 1; // interface identifier option
2099 q
[5] = 10; // option length
2100 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2101 *(uint32_t *) (q
+ 10) = 0;
2104 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2105 restart_timer(s
, ipv6cp
);
2108 static void sessionclear(sessionidt s
)
2110 memset(&session
[s
], 0, sizeof(session
[s
]));
2111 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2112 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2114 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2115 session
[s
].next
= sessionfree
;
2119 // kill a session now
2120 void sessionkill(sessionidt s
, char *reason
)
2124 if (!session
[s
].opened
) // not alive
2127 if (session
[s
].next
)
2129 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2133 if (!session
[s
].die
)
2134 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2136 if (sess_local
[s
].radius
)
2137 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2139 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2141 cluster_send_session(s
);
2144 static void tunnelclear(tunnelidt t
)
2147 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2148 tunnel
[t
].state
= TUNNELFREE
;
2151 static void bundleclear(bundleidt b
)
2154 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2155 bundle
[b
].state
= BUNDLEFREE
;
2158 // kill a tunnel now
2159 static void tunnelkill(tunnelidt t
, char *reason
)
2166 tunnel
[t
].state
= TUNNELDIE
;
2168 // free control messages
2169 while ((c
= tunnel
[t
].controls
))
2171 controlt
* n
= c
->next
;
2172 tunnel
[t
].controls
= n
;
2173 tunnel
[t
].controlc
--;
2174 c
->next
= controlfree
;
2178 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2179 if (session
[s
].tunnel
== t
)
2180 sessionkill(s
, reason
);
2184 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2185 cli_tunnel_actions
[t
].action
= 0;
2186 cluster_send_tunnel(t
);
2189 // shut down a tunnel cleanly
2190 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2194 CSTAT(tunnelshutdown
);
2196 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2198 // never set up, can immediately kill
2199 tunnelkill(t
, reason
);
2202 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2205 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2206 if (session
[s
].tunnel
== t
)
2207 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2209 tunnel
[t
].state
= TUNNELDIE
;
2210 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2211 cluster_send_tunnel(t
);
2212 // TBA - should we wait for sessions to stop?
2215 controlt
*c
= controlnew(4); // sending StopCCN
2220 *(uint16_t *) buf
= htons(result
);
2221 *(uint16_t *) (buf
+2) = htons(error
);
2224 int m
= strlen(msg
);
2225 if (m
+ 4 > sizeof(buf
))
2226 m
= sizeof(buf
) - 4;
2228 memcpy(buf
+4, msg
, m
);
2232 controlb(c
, 1, buf
, l
, 1);
2235 control16(c
, 1, result
, 1);
2237 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2238 controladd(c
, 0, t
); // send the message
2242 // read and process packet on tunnel (UDP)
2243 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2245 uint8_t *chapresponse
= NULL
;
2246 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2247 uint8_t *p
= buf
+ 2;
2254 LOG_HEX(5, "UDP Data", buf
, len
);
2255 STAT(tunnel_rx_packets
);
2256 INC_STAT(tunnel_rx_bytes
, len
);
2259 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2260 STAT(tunnel_rx_errors
);
2263 if ((buf
[1] & 0x0F) != 2)
2265 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2266 STAT(tunnel_rx_errors
);
2271 l
= ntohs(*(uint16_t *) p
);
2274 t
= ntohs(*(uint16_t *) p
);
2276 s
= ntohs(*(uint16_t *) p
);
2278 if (s
>= MAXSESSION
)
2280 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2281 STAT(tunnel_rx_errors
);
2286 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2287 STAT(tunnel_rx_errors
);
2292 ns
= ntohs(*(uint16_t *) p
);
2294 nr
= ntohs(*(uint16_t *) p
);
2299 uint16_t o
= ntohs(*(uint16_t *) p
);
2304 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2305 STAT(tunnel_rx_errors
);
2310 // used to time out old tunnels
2311 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2312 tunnel
[t
].lastrec
= time_now
;
2316 uint16_t message
= 0xFFFF; // message type
2318 uint8_t mandatory
= 0;
2319 uint16_t asession
= 0; // assigned session
2320 uint32_t amagic
= 0; // magic number
2321 uint8_t aflags
= 0; // flags from last LCF
2322 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2323 char called
[MAXTEL
] = ""; // called number
2324 char calling
[MAXTEL
] = ""; // calling number
2326 if (!config
->cluster_iam_master
)
2328 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2332 // control messages must have bits 0x80|0x40|0x08
2333 // (type, length and sequence) set, and bits 0x02|0x01
2334 // (offset and priority) clear
2335 if ((*buf
& 0xCB) != 0xC8)
2337 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2338 STAT(tunnel_rx_errors
);
2342 // check for duplicate tunnel open message
2348 // Is this a duplicate of the first packet? (SCCRQ)
2350 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2352 if (tunnel
[i
].state
!= TUNNELOPENING
||
2353 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2354 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2357 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2362 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2363 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2365 // if no tunnel specified, assign one
2368 if (!(t
= new_tunnel()))
2370 LOG(1, 0, 0, "No more tunnels\n");
2371 STAT(tunnel_overflow
);
2375 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2376 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2377 tunnel
[t
].window
= 4; // default window
2378 STAT(tunnel_created
);
2379 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2380 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2383 // If the 'ns' just received is not the 'nr' we're
2384 // expecting, just send an ack and drop it.
2386 // if 'ns' is less, then we got a retransmitted packet.
2387 // if 'ns' is greater than missed a packet. Either way
2388 // we should ignore it.
2389 if (ns
!= tunnel
[t
].nr
)
2391 // is this the sequence we were expecting?
2392 STAT(tunnel_rx_errors
);
2393 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2394 t
, ns
, tunnel
[t
].nr
);
2396 if (l
) // Is this not a ZLB?
2401 // check sequence of this message
2403 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2404 // some to clear maybe?
2405 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2407 controlt
*c
= tunnel
[t
].controls
;
2408 tunnel
[t
].controls
= c
->next
;
2409 tunnel
[t
].controlc
--;
2410 c
->next
= controlfree
;
2413 tunnel
[t
].try = 0; // we have progress
2416 // receiver advance (do here so quoted correctly in any sends below)
2417 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2418 if (skip
< 0) skip
= 0;
2419 if (skip
< tunnel
[t
].controlc
)
2421 // some control packets can now be sent that were previous stuck out of window
2422 int tosend
= tunnel
[t
].window
- skip
;
2423 controlt
*c
= tunnel
[t
].controls
;
2431 tunnel
[t
].try = 0; // first send
2432 tunnelsend(c
->buf
, c
->length
, t
);
2437 if (!tunnel
[t
].controlc
)
2438 tunnel
[t
].retry
= 0; // caught up
2441 { // if not a null message
2446 // Default disconnect cause/message on receipt of CDN. Set to
2447 // more specific value from attribute 1 (result code) or 46
2448 // (disconnect cause) if present below.
2449 int disc_cause_set
= 0;
2450 int disc_cause
= TERM_NAS_REQUEST
;
2451 char const *disc_reason
= "Closed (Received CDN).";
2454 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2456 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2463 LOG(1, s
, t
, "Invalid length in AVP\n");
2464 STAT(tunnel_rx_errors
);
2469 if (flags
& 0x3C) // reserved bits, should be clear
2471 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2473 result
= 2; // general error
2474 error
= 3; // reserved field non-zero
2479 if (*(uint16_t *) (b
))
2481 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2483 result
= 2; // general error
2484 error
= 6; // generic vendor-specific error
2485 msg
= "unsupported vendor-specific";
2489 mtype
= ntohs(*(uint16_t *) (b
));
2497 // handle hidden AVPs
2498 if (!*config
->l2tp_secret
)
2500 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2502 result
= 2; // general error
2503 error
= 6; // generic vendor-specific error
2504 msg
= "secret not specified";
2507 if (!session
[s
].random_vector_length
)
2509 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2511 result
= 2; // general error
2512 error
= 6; // generic
2513 msg
= "no random vector";
2518 LOG(2, s
, t
, "Short hidden AVP.\n");
2520 result
= 2; // general error
2521 error
= 2; // length is wrong
2527 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2529 orig_len
= ntohs(*(uint16_t *) b
);
2530 if (orig_len
> n
+ 2)
2532 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2536 result
= 2; // general error
2537 error
= 2; // length is wrong
2546 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2547 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2551 case 0: // message type
2552 message
= ntohs(*(uint16_t *) b
);
2553 mandatory
= flags
& 0x80;
2554 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2556 case 1: // result code
2558 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2559 char const *resdesc
= "(unknown)";
2560 char const *errdesc
= NULL
;
2565 resdesc
= l2tp_stopccn_result_code(rescode
);
2566 cause
= TERM_LOST_SERVICE
;
2568 else if (message
== 14)
2570 resdesc
= l2tp_cdn_result_code(rescode
);
2572 cause
= TERM_LOST_CARRIER
;
2574 cause
= TERM_ADMIN_RESET
;
2577 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2580 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2581 errdesc
= l2tp_error_code(errcode
);
2582 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2585 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2587 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2589 disc_cause_set
= mtype
;
2590 disc_reason
= errdesc
? errdesc
: resdesc
;
2597 case 2: // protocol version
2599 version
= ntohs(*(uint16_t *) (b
));
2600 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2601 if (version
&& version
!= 0x0100)
2602 { // allow 0.0 and 1.0
2603 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2605 result
= 5; // unspported protocol version
2606 error
= 0x0100; // supported version
2612 case 3: // framing capabilities
2614 case 4: // bearer capabilities
2616 case 5: // tie breaker
2617 // We never open tunnels, so we don't care about tie breakers
2619 case 6: // firmware revision
2621 case 7: // host name
2622 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2623 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2624 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2625 // TBA - to send to RADIUS
2627 case 8: // vendor name
2628 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2629 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2630 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2632 case 9: // assigned tunnel
2633 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2634 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2636 case 10: // rx window
2637 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2638 if (!tunnel
[t
].window
)
2639 tunnel
[t
].window
= 1; // window of 0 is silly
2640 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2642 case 11: // Challenge
2644 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2645 build_chap_response(b
, 2, n
, &chapresponse
);
2648 case 13: // Response
2649 // Why did they send a response? We never challenge.
2650 LOG(2, s
, t
, " received unexpected challenge response\n");
2653 case 14: // assigned session
2654 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2655 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2657 case 15: // call serial number
2658 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2660 case 18: // bearer type
2661 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2664 case 19: // framing type
2665 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2668 case 21: // called number
2669 memset(called
, 0, sizeof(called
));
2670 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2671 LOG(4, s
, t
, " Called <%s>\n", called
);
2673 case 22: // calling number
2674 memset(calling
, 0, sizeof(calling
));
2675 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2676 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2680 case 24: // tx connect speed
2683 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2687 // AS5300s send connect speed as a string
2689 memset(tmp
, 0, sizeof(tmp
));
2690 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2691 session
[s
].tx_connect_speed
= atol(tmp
);
2693 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2695 case 38: // rx connect speed
2698 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2702 // AS5300s send connect speed as a string
2704 memset(tmp
, 0, sizeof(tmp
));
2705 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2706 session
[s
].rx_connect_speed
= atol(tmp
);
2708 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2710 case 25: // Physical Channel ID
2712 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2713 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2716 case 29: // Proxy Authentication Type
2718 uint16_t atype
= ntohs(*(uint16_t *)b
);
2719 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2722 case 30: // Proxy Authentication Name
2725 memset(authname
, 0, sizeof(authname
));
2726 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2727 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2731 case 31: // Proxy Authentication Challenge
2733 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2736 case 32: // Proxy Authentication ID
2738 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2739 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2742 case 33: // Proxy Authentication Response
2743 LOG(4, s
, t
, " Proxy Auth Response\n");
2745 case 27: // last sent lcp
2746 { // find magic number
2747 uint8_t *p
= b
, *e
= p
+ n
;
2748 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2750 if (*p
== 5 && p
[1] == 6) // Magic-Number
2751 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2752 else if (*p
== 7) // Protocol-Field-Compression
2753 aflags
|= SESSION_PFC
;
2754 else if (*p
== 8) // Address-and-Control-Field-Compression
2755 aflags
|= SESSION_ACFC
;
2760 case 28: // last recv lcp confreq
2762 case 26: // Initial Received LCP CONFREQ
2764 case 39: // seq required - we control it as an LNS anyway...
2766 case 36: // Random Vector
2767 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2768 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2769 if (n
> sizeof(session
[s
].random_vector
))
2770 n
= sizeof(session
[s
].random_vector
);
2771 memcpy(session
[s
].random_vector
, b
, n
);
2772 session
[s
].random_vector_length
= n
;
2774 case 46: // ppp disconnect cause
2777 uint16_t code
= ntohs(*(uint16_t *) b
);
2778 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2779 uint8_t dir
= *(b
+ 4);
2781 LOG(4, s
, t
, " PPP disconnect cause "
2782 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2783 code
, proto
, dir
, n
- 5, b
+ 5);
2785 disc_cause_set
= mtype
;
2789 case 1: // admin disconnect
2790 disc_cause
= TERM_ADMIN_RESET
;
2791 disc_reason
= "Administrative disconnect";
2793 case 3: // lcp terminate
2794 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2795 disc_cause
= TERM_USER_REQUEST
;
2796 disc_reason
= "Normal disconnection";
2798 case 4: // compulsory encryption unavailable
2799 if (dir
!= 1) break; // 1=refused by peer, 2=local
2800 disc_cause
= TERM_USER_ERROR
;
2801 disc_reason
= "Compulsory encryption refused";
2803 case 5: // lcp: fsm timeout
2804 disc_cause
= TERM_PORT_ERROR
;
2805 disc_reason
= "LCP: FSM timeout";
2807 case 6: // lcp: no recognisable lcp packets received
2808 disc_cause
= TERM_PORT_ERROR
;
2809 disc_reason
= "LCP: no recognisable LCP packets";
2811 case 7: // lcp: magic-no error (possibly looped back)
2812 disc_cause
= TERM_PORT_ERROR
;
2813 disc_reason
= "LCP: magic-no error (possible loop)";
2815 case 8: // lcp: echo request timeout
2816 disc_cause
= TERM_PORT_ERROR
;
2817 disc_reason
= "LCP: echo request timeout";
2819 case 13: // auth: fsm timeout
2820 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2821 disc_reason
= "Authentication: FSM timeout";
2823 case 15: // auth: unacceptable auth protocol
2824 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2825 disc_reason
= "Unacceptable authentication protocol";
2827 case 16: // auth: authentication failed
2828 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2829 disc_reason
= "Authentication failed";
2831 case 17: // ncp: fsm timeout
2832 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2833 disc_reason
= "NCP: FSM timeout";
2835 case 18: // ncp: no ncps available
2836 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2837 disc_reason
= "NCP: no NCPs available";
2839 case 19: // ncp: failure to converge on acceptable address
2840 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2841 disc_reason
= (dir
== 1)
2842 ? "NCP: too many Configure-Naks received from peer"
2843 : "NCP: too many Configure-Naks sent to peer";
2845 case 20: // ncp: user not permitted to use any address
2846 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2847 disc_reason
= (dir
== 1)
2848 ? "NCP: local link address not acceptable to peer"
2849 : "NCP: remote link address not acceptable";
2856 static char e
[] = "unknown AVP 0xXXXX";
2857 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2859 result
= 2; // general error
2860 error
= 8; // unknown mandatory AVP
2861 sprintf((msg
= e
) + 14, "%04x", mtype
);
2868 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2872 case 1: // SCCRQ - Start Control Connection Request
2873 tunnel
[t
].state
= TUNNELOPENING
;
2874 if (main_quit
!= QUIT_SHUTDOWN
)
2876 controlt
*c
= controlnew(2); // sending SCCRP
2877 control16(c
, 2, version
, 1); // protocol version
2878 control32(c
, 3, 3, 1); // framing
2879 controls(c
, 7, hostname
, 1); // host name
2880 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2881 control16(c
, 9, t
, 1); // assigned tunnel
2882 controladd(c
, 0, t
); // send the resply
2886 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2890 tunnel
[t
].state
= TUNNELOPEN
;
2891 tunnel
[t
].lastrec
= time_now
;
2894 tunnel
[t
].state
= TUNNELOPEN
;
2895 tunnel
[t
].lastrec
= time_now
;
2896 controlnull(t
); // ack
2899 controlnull(t
); // ack
2900 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2903 controlnull(t
); // simply ACK
2915 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2917 controlt
*c
= controlnew(11); // ICRP
2920 sessionfree
= session
[s
].next
;
2921 memset(&session
[s
], 0, sizeof(session
[s
]));
2923 if (s
> config
->cluster_highest_sessionid
)
2924 config
->cluster_highest_sessionid
= s
;
2926 session
[s
].opened
= time_now
;
2927 session
[s
].tunnel
= t
;
2928 session
[s
].far
= asession
;
2929 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2930 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2931 control16(c
, 14, s
, 1); // assigned session
2932 controladd(c
, asession
, t
); // send the reply
2934 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2935 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2937 session
[s
].ppp
.phase
= Establish
;
2938 session
[s
].ppp
.lcp
= Starting
;
2940 STAT(session_created
);
2945 controlt
*c
= controlnew(14); // CDN
2948 STAT(session_overflow
);
2949 LOG(1, 0, t
, "No free sessions\n");
2950 control16(c
, 1, 4, 0); // temporary lack of resources
2953 control16(c
, 1, 2, 7); // shutting down, try another
2955 controladd(c
, asession
, t
); // send the message
2962 if (amagic
== 0) amagic
= time_now
;
2963 session
[s
].magic
= amagic
; // set magic number
2964 session
[s
].flags
= aflags
; // set flags received
2965 session
[s
].mru
= PPPoE_MRU
; // default
2966 controlnull(t
); // ack
2969 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
2970 sess_local
[s
].ppp_mru
= MRU
;
2972 // Set multilink options before sending initial LCP packet
2973 sess_local
[s
].mp_mrru
= 1614;
2974 sess_local
[s
].mp_epdis
= config
->bind_address
? config
->bind_address
: my_address
;
2977 change_state(s
, lcp
, RequestSent
);
2981 controlnull(t
); // ack
2982 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
2985 LOG(1, s
, t
, "Missing message type\n");
2988 STAT(tunnel_rx_errors
);
2990 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2992 LOG(1, s
, t
, "Unknown message type %u\n", message
);
2995 if (chapresponse
) free(chapresponse
);
2996 cluster_send_tunnel(t
);
3000 LOG(4, s
, t
, " Got a ZLB ack\n");
3007 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3008 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3009 { // HDLC address header, discard
3015 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3016 STAT(tunnel_rx_errors
);
3026 proto
= ntohs(*(uint16_t *) p
);
3031 if (s
&& !session
[s
].opened
) // Is something wrong??
3033 if (!config
->cluster_iam_master
)
3035 // Pass it off to the master to deal with..
3036 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3041 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3042 STAT(tunnel_rx_errors
);
3046 if (proto
== PPPPAP
)
3048 session
[s
].last_packet
= time_now
;
3049 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3050 processpap(s
, t
, p
, l
);
3052 else if (proto
== PPPCHAP
)
3054 session
[s
].last_packet
= time_now
;
3055 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3056 processchap(s
, t
, p
, l
);
3058 else if (proto
== PPPLCP
)
3060 session
[s
].last_packet
= time_now
;
3061 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3062 processlcp(s
, t
, p
, l
);
3064 else if (proto
== PPPIPCP
)
3066 session
[s
].last_packet
= time_now
;
3067 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3068 processipcp(s
, t
, p
, l
);
3070 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3072 session
[s
].last_packet
= time_now
;
3073 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3074 processipv6cp(s
, t
, p
, l
);
3076 else if (proto
== PPPCCP
)
3078 session
[s
].last_packet
= time_now
;
3079 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3080 processccp(s
, t
, p
, l
);
3082 else if (proto
== PPPIP
)
3086 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3087 return; // closing session, PPP not processed
3090 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3091 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3093 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3097 processipin(s
, t
, p
, l
);
3099 else if (proto
== PPPMP
)
3103 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3104 return; // closing session, PPP not processed
3107 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3108 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3110 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3114 processmpin(s
, t
, p
, l
);
3116 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3120 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3121 return; // closing session, PPP not processed
3124 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3125 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3127 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3131 processipv6in(s
, t
, p
, l
);
3133 else if (session
[s
].ppp
.lcp
== Opened
)
3135 session
[s
].last_packet
= time_now
;
3136 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3137 protoreject(s
, t
, p
, l
, proto
);
3141 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3142 proto
, ppp_state(session
[s
].ppp
.lcp
));
3147 // read and process packet on tun
3148 static void processtun(uint8_t * buf
, int len
)
3150 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3151 STAT(tun_rx_packets
);
3152 INC_STAT(tun_rx_bytes
, len
);
3160 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3161 STAT(tun_rx_errors
);
3165 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3166 processipout(buf
, len
);
3167 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3168 && config
->ipv6_prefix
.s6_addr
[0])
3169 processipv6out(buf
, len
);
3174 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3175 // that we look at the whole of the tunnel, radius and session tables
3177 static void regular_cleanups(double period
)
3179 // Next tunnel, radius and session to check for actions on.
3180 static tunnelidt t
= 0;
3182 static sessionidt s
= 0;
3195 // divide up tables into slices based on the last run
3196 t_slice
= config
->cluster_highest_tunnelid
* period
;
3197 r_slice
= (MAXRADIUS
- 1) * period
;
3198 s_slice
= config
->cluster_highest_sessionid
* period
;
3202 else if (t_slice
> config
->cluster_highest_tunnelid
)
3203 t_slice
= config
->cluster_highest_tunnelid
;
3207 else if (r_slice
> (MAXRADIUS
- 1))
3208 r_slice
= MAXRADIUS
- 1;
3212 else if (s_slice
> config
->cluster_highest_sessionid
)
3213 s_slice
= config
->cluster_highest_sessionid
;
3215 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3217 for (i
= 0; i
< t_slice
; i
++)
3220 if (t
> config
->cluster_highest_tunnelid
)
3223 // check for expired tunnels
3224 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3226 STAT(tunnel_timeout
);
3227 tunnelkill(t
, "Expired");
3231 // check for message resend
3232 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3234 // resend pending messages as timeout on reply
3235 if (tunnel
[t
].retry
<= TIME
)
3237 controlt
*c
= tunnel
[t
].controls
;
3238 uint16_t w
= tunnel
[t
].window
;
3239 tunnel
[t
].try++; // another try
3240 if (tunnel
[t
].try > 5)
3241 tunnelkill(t
, "Timeout on control message"); // game over
3245 tunnelsend(c
->buf
, c
->length
, t
);
3253 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3255 controlt
*c
= controlnew(6); // sending HELLO
3256 controladd(c
, 0, t
); // send the message
3257 LOG(3, 0, t
, "Sending HELLO message\n");
3261 // Check for tunnel changes requested from the CLI
3262 if ((a
= cli_tunnel_actions
[t
].action
))
3264 cli_tunnel_actions
[t
].action
= 0;
3265 if (a
& CLI_TUN_KILL
)
3267 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3268 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3274 for (i
= 0; i
< r_slice
; i
++)
3280 if (!radius
[r
].state
)
3283 if (radius
[r
].retry
<= TIME
)
3290 for (i
= 0; i
< s_slice
; i
++)
3293 if (s
> config
->cluster_highest_sessionid
)
3296 if (!session
[s
].opened
) // Session isn't in use
3299 // check for expired sessions
3302 if (session
[s
].die
<= TIME
)
3304 sessionkill(s
, "Expired");
3311 if (sess_local
[s
].lcp
.restart
<= time_now
)
3313 int next_state
= session
[s
].ppp
.lcp
;
3314 switch (session
[s
].ppp
.lcp
)
3318 next_state
= RequestSent
;
3321 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3323 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3324 sendlcp(s
, session
[s
].tunnel
);
3325 change_state(s
, lcp
, next_state
);
3329 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3330 STAT(session_timeout
);
3340 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3342 int next_state
= session
[s
].ppp
.ipcp
;
3343 switch (session
[s
].ppp
.ipcp
)
3347 next_state
= RequestSent
;
3350 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3352 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3353 sendipcp(s
, session
[s
].tunnel
);
3354 change_state(s
, ipcp
, next_state
);
3358 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3359 STAT(session_timeout
);
3369 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3371 int next_state
= session
[s
].ppp
.ipv6cp
;
3372 switch (session
[s
].ppp
.ipv6cp
)
3376 next_state
= RequestSent
;
3379 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3381 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3382 sendipv6cp(s
, session
[s
].tunnel
);
3383 change_state(s
, ipv6cp
, next_state
);
3387 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3388 change_state(s
, ipv6cp
, Stopped
);
3395 if (sess_local
[s
].ccp
.restart
<= time_now
)
3397 int next_state
= session
[s
].ppp
.ccp
;
3398 switch (session
[s
].ppp
.ccp
)
3402 next_state
= RequestSent
;
3405 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3407 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3408 sendccp(s
, session
[s
].tunnel
);
3409 change_state(s
, ccp
, next_state
);
3413 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3414 change_state(s
, ccp
, Stopped
);
3421 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3422 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3424 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3425 STAT(session_timeout
);
3430 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3431 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3432 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3434 uint8_t b
[MAXETHER
];
3436 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3440 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3441 *(uint16_t *)(q
+ 2) = htons(8); // Length
3442 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3444 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3445 (int)(time_now
- session
[s
].last_packet
));
3446 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3447 sess_local
[s
].last_echo
= time_now
;
3451 // Drop sessions who have reached session_timeout seconds
3452 if (session
[s
].session_timeout
)
3454 bundleidt bid
= session
[s
].bundle
;
3457 if (time_now
- bundle
[bid
].last_check
>= 1)
3459 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3460 bundle
[bid
].last_check
= time_now
;
3461 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3464 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3466 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3473 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3475 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3481 // Drop sessions who have reached idle_timeout seconds
3482 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3484 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3485 STAT(session_timeout
);
3490 // Check for actions requested from the CLI
3491 if ((a
= cli_session_actions
[s
].action
))
3495 cli_session_actions
[s
].action
= 0;
3496 if (a
& CLI_SESS_KILL
)
3498 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3499 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3500 a
= 0; // dead, no need to check for other actions
3504 if (a
& CLI_SESS_NOSNOOP
)
3506 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3507 session
[s
].snoop_ip
= 0;
3508 session
[s
].snoop_port
= 0;
3512 else if (a
& CLI_SESS_SNOOP
)
3514 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3515 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3516 cli_session_actions
[s
].snoop_port
);
3518 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3519 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3524 if (a
& CLI_SESS_NOTHROTTLE
)
3526 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3527 throttle_session(s
, 0, 0);
3531 else if (a
& CLI_SESS_THROTTLE
)
3533 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3534 cli_session_actions
[s
].throttle_in
,
3535 cli_session_actions
[s
].throttle_out
);
3537 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3542 if (a
& CLI_SESS_NOFILTER
)
3544 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3545 filter_session(s
, 0, 0);
3549 else if (a
& CLI_SESS_FILTER
)
3551 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3552 cli_session_actions
[s
].filter_in
,
3553 cli_session_actions
[s
].filter_out
);
3555 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3561 cluster_send_session(s
);
3564 // RADIUS interim accounting
3565 if (config
->radius_accounting
&& config
->radius_interim
> 0
3566 && session
[s
].ip
&& !session
[s
].walled_garden
3567 && !sess_local
[s
].radius
// RADIUS already in progress
3568 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3569 && session
[s
].flags
& SESSION_STARTED
)
3571 int rad
= radiusnew(s
);
3574 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3575 STAT(radius_overflow
);
3579 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3580 session
[s
].user
, session
[s
].unique_id
);
3582 radiussend(rad
, RADIUSINTERIM
);
3583 sess_local
[s
].last_interim
= time_now
;
3588 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3589 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3593 // Are we in the middle of a tunnel update, or radius
3596 static int still_busy(void)
3599 static clockt last_talked
= 0;
3600 static clockt start_busy_wait
= 0;
3602 if (!config
->cluster_iam_master
)
3605 static time_t stopped_bgp
= 0;
3610 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3612 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3613 if (bgp_peers
[i
].state
== Established
)
3614 bgp_stop(&bgp_peers
[i
]);
3616 stopped_bgp
= time_now
;
3618 // we don't want to become master
3619 cluster_send_ping(0);
3624 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
3632 if (main_quit
== QUIT_SHUTDOWN
)
3634 static int dropped
= 0;
3639 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3640 for (i
= 1; i
< MAXTUNNEL
; i
++)
3641 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3642 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3648 if (start_busy_wait
== 0)
3649 start_busy_wait
= TIME
;
3651 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3653 if (!tunnel
[i
].controlc
)
3656 if (last_talked
!= TIME
)
3658 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3664 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3665 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3667 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3671 for (i
= 1; i
< MAXRADIUS
; i
++)
3673 if (radius
[i
].state
== RADIUSNULL
)
3675 if (radius
[i
].state
== RADIUSWAIT
)
3678 if (last_talked
!= TIME
)
3680 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3690 # include <sys/epoll.h>
3692 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3693 # include "fake_epoll.h"
3696 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3699 // additional polled fds
3701 # define EXTRA_FDS BGP_NUM_PEERS
3703 # define EXTRA_FDS 0
3706 // main loop - gets packets on tun or udp and processes them
3707 static void mainloop(void)
3711 clockt next_cluster_ping
= 0; // send initial ping immediately
3712 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3713 int maxevent
= sizeof(events
)/sizeof(*events
);
3715 if ((epollfd
= epoll_create(maxevent
)) < 0)
3717 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3721 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3722 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3724 /* setup our fds to poll for input */
3726 static struct event_data d
[BASE_FDS
];
3727 struct epoll_event e
;
3734 d
[i
].type
= FD_TYPE_CLI
;
3735 e
.data
.ptr
= &d
[i
++];
3736 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3739 d
[i
].type
= FD_TYPE_CLUSTER
;
3740 e
.data
.ptr
= &d
[i
++];
3741 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3743 d
[i
].type
= FD_TYPE_TUN
;
3744 e
.data
.ptr
= &d
[i
++];
3745 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3747 d
[i
].type
= FD_TYPE_UDP
;
3748 e
.data
.ptr
= &d
[i
++];
3749 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3751 d
[i
].type
= FD_TYPE_CONTROL
;
3752 e
.data
.ptr
= &d
[i
++];
3753 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3755 d
[i
].type
= FD_TYPE_DAE
;
3756 e
.data
.ptr
= &d
[i
++];
3757 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3759 d
[i
].type
= FD_TYPE_NETLINK
;
3760 e
.data
.ptr
= &d
[i
++];
3761 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3765 signal(SIGPIPE
, SIG_IGN
);
3766 bgp_setup(config
->as_number
);
3767 if (config
->bind_address
)
3768 bgp_add_route(config
->bind_address
, 0xffffffff);
3770 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3772 if (config
->neighbour
[i
].name
[0])
3773 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3774 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3775 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3779 while (!main_quit
|| still_busy())
3789 config
->reload_config
++;
3792 if (config
->reload_config
)
3794 config
->reload_config
= 0;
3802 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3803 STAT(select_called
);
3808 if (errno
== EINTR
||
3809 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3812 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3818 struct sockaddr_in addr
;
3819 struct in_addr local
;
3824 int cluster_ready
= 0;
3827 int cluster_pkts
= 0;
3829 uint32_t bgp_events
[BGP_NUM_PEERS
];
3830 memset(bgp_events
, 0, sizeof(bgp_events
));
3833 for (c
= n
, i
= 0; i
< c
; i
++)
3835 struct event_data
*d
= events
[i
].data
.ptr
;
3839 case FD_TYPE_CLI
: // CLI connections
3843 alen
= sizeof(addr
);
3844 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3850 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3856 // these are handled below, with multiple interleaved reads
3857 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3858 case FD_TYPE_TUN
: tun_ready
++; break;
3859 case FD_TYPE_UDP
: udp_ready
++; break;
3861 case FD_TYPE_CONTROL
: // nsctl commands
3862 alen
= sizeof(addr
);
3863 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3864 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3868 case FD_TYPE_DAE
: // DAE requests
3869 alen
= sizeof(addr
);
3870 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3871 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3875 case FD_TYPE_RADIUS
: // RADIUS response
3876 alen
= sizeof(addr
);
3877 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3878 if (s
>= 0 && config
->cluster_iam_master
)
3880 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3881 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3882 processrad(buf
, s
, d
->index
);
3884 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3885 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3893 bgp_events
[d
->index
] = events
[i
].events
;
3898 case FD_TYPE_NETLINK
:
3900 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
3901 s
= netlink_recv(buf
, sizeof(buf
));
3902 if (nh
->nlmsg_type
== NLMSG_ERROR
)
3904 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
3907 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
3909 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
3914 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
3919 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
);
3925 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3930 bgp_process(bgp_events
);
3933 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3938 alen
= sizeof(addr
);
3939 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3941 processudp(buf
, s
, &addr
);
3954 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3969 alen
= sizeof(addr
);
3970 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3972 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3983 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3984 STAT(multi_read_used
);
3986 if (c
>= config
->multi_read_count
)
3988 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3989 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3991 STAT(multi_read_exceeded
);
3998 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4000 // Log current traffic stats
4001 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4002 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4003 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4004 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4005 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4007 udp_tx
= udp_rx
= 0;
4008 udp_rx_pkt
= eth_rx_pkt
= 0;
4009 eth_tx
= eth_rx
= 0;
4012 if (config
->dump_speed
)
4013 printf("%s\n", config
->bandwidth
);
4015 // Update the internal time counter
4016 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4020 struct param_timer p
= { time_now
};
4021 run_plugins(PLUGIN_TIMER
, &p
);
4025 // Runs on every machine (master and slaves).
4026 if (next_cluster_ping
<= TIME
)
4028 // Check to see which of the cluster is still alive..
4030 cluster_send_ping(basetime
); // Only does anything if we're a slave
4031 cluster_check_master(); // ditto.
4033 cluster_heartbeat(); // Only does anything if we're a master.
4034 cluster_check_slaves(); // ditto.
4036 master_update_counts(); // If we're a slave, send our byte counters to our master.
4038 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4039 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4041 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4044 if (!config
->cluster_iam_master
)
4047 // Run token bucket filtering queue..
4048 // Only run it every 1/10th of a second.
4050 static clockt last_run
= 0;
4051 if (last_run
!= TIME
)
4058 // Handle timeouts, retries etc.
4060 static double last_clean
= 0;
4064 TIME
= now(&this_clean
);
4065 diff
= this_clean
- last_clean
;
4067 // Run during idle time (after we've handled
4068 // all incoming packets) or every 1/10th sec
4069 if (!more
|| diff
> 0.1)
4071 regular_cleanups(diff
);
4072 last_clean
= this_clean
;
4076 if (*config
->accounting_dir
)
4078 static clockt next_acct
= 0;
4079 static clockt next_shut_acct
= 0;
4081 if (next_acct
<= TIME
)
4083 // Dump accounting data
4084 next_acct
= TIME
+ ACCT_TIME
;
4085 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4088 else if (next_shut_acct
<= TIME
)
4090 // Dump accounting data for shutdown sessions
4091 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4098 // Are we the master and shutting down??
4099 if (config
->cluster_iam_master
)
4100 cluster_heartbeat(); // Flush any queued changes..
4102 // Ok. Notify everyone we're shutting down. If we're
4103 // the master, this will force an election.
4104 cluster_send_ping(0);
4107 // Important!!! We MUST not process any packets past this point!
4108 LOG(1, 0, 0, "Shutdown complete\n");
4111 static void stripdomain(char *host
)
4115 if ((p
= strchr(host
, '.')))
4121 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4127 while (fgets(buf
, sizeof(buf
), resolv
))
4129 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4132 if (!isspace(buf
[6]))
4136 while (isspace(*b
)) b
++;
4141 while (*b
&& !isspace(*b
)) b
++;
4143 if (buf
[0] == 'd') // domain is canonical
4149 // first search line
4152 // hold, may be subsequent domain line
4153 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4164 int hl
= strlen(host
);
4165 int dl
= strlen(domain
);
4166 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4167 host
[hl
-dl
- 1] = 0;
4171 *p
= 0; // everything after first dot
4176 // Init data structures
4177 static void initdata(int optdebug
, char *optconfig
)
4181 if (!(config
= shared_malloc(sizeof(configt
))))
4183 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4187 memset(config
, 0, sizeof(configt
));
4188 time(&config
->start_time
);
4189 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4190 config
->debug
= optdebug
;
4191 config
->num_tbfs
= MAXTBFS
;
4192 config
->rl_rate
= 28; // 28kbps
4193 config
->cluster_mcast_ttl
= 1;
4194 config
->cluster_master_min_adv
= 1;
4195 config
->ppp_restart_time
= 3;
4196 config
->ppp_max_configure
= 10;
4197 config
->ppp_max_failure
= 5;
4198 config
->kill_timedout_sessions
= 1;
4199 strcpy(config
->random_device
, RANDOMDEVICE
);
4201 log_stream
= stderr
;
4204 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4206 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4209 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4212 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4214 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4217 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4219 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4222 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4224 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4227 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4229 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4232 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4234 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4238 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4240 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4244 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4246 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4250 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4252 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4256 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4258 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4261 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4263 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4265 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4268 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4270 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4272 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4275 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4277 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4278 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4279 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4280 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4281 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4283 // Put all the sessions on the free list marked as undefined.
4284 for (i
= 1; i
< MAXSESSION
; i
++)
4286 session
[i
].next
= i
+ 1;
4287 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4289 session
[MAXSESSION
- 1].next
= 0;
4292 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4293 for (i
= 1; i
< MAXTUNNEL
; i
++)
4294 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4296 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4297 bundle
[i
].state
= BUNDLEUNDEF
;
4302 // Grab my hostname unless it's been specified
4303 gethostname(hostname
, sizeof(hostname
));
4304 stripdomain(hostname
);
4307 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4310 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4312 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4318 static int assign_ip_address(sessionidt s
)
4322 time_t best_time
= time_now
;
4323 char *u
= session
[s
].user
;
4327 CSTAT(assign_ip_address
);
4329 for (i
= 1; i
< ip_pool_size
; i
++)
4331 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4334 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4341 if (ip_address_pool
[i
].last
< best_time
)
4344 if (!(best_time
= ip_address_pool
[i
].last
))
4345 break; // never used, grab this one
4351 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4355 session
[s
].ip
= ip_address_pool
[best
].address
;
4356 session
[s
].ip_pool_index
= best
;
4357 ip_address_pool
[best
].assigned
= 1;
4358 ip_address_pool
[best
].last
= time_now
;
4359 ip_address_pool
[best
].session
= s
;
4360 if (session
[s
].walled_garden
)
4361 /* Don't track addresses of users in walled garden (note: this
4362 means that their address isn't "sticky" even if they get
4364 ip_address_pool
[best
].user
[0] = 0;
4366 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4369 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4370 reuse
? "Reusing" : "Allocating", best
);
4375 static void free_ip_address(sessionidt s
)
4377 int i
= session
[s
].ip_pool_index
;
4380 CSTAT(free_ip_address
);
4383 return; // what the?
4385 if (i
< 0) // Is this actually part of the ip pool?
4389 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4391 ip_address_pool
[i
].assigned
= 0;
4392 ip_address_pool
[i
].session
= 0;
4393 ip_address_pool
[i
].last
= time_now
;
4397 // Fsck the address pool against the session table.
4398 // Normally only called when we become a master.
4400 // This isn't perfect: We aren't keep tracking of which
4401 // users used to have an IP address.
4403 void rebuild_address_pool(void)
4408 // Zero the IP pool allocation, and build
4409 // a map from IP address to pool index.
4410 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4412 ip_address_pool
[i
].assigned
= 0;
4413 ip_address_pool
[i
].session
= 0;
4414 if (!ip_address_pool
[i
].address
)
4417 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4420 for (i
= 0; i
< MAXSESSION
; ++i
)
4423 if (!(session
[i
].opened
&& session
[i
].ip
))
4426 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4428 if (session
[i
].ip_pool_index
< 0)
4430 // Not allocated out of the pool.
4431 if (ipid
< 1) // Not found in the pool either? good.
4434 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4435 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4437 // Fall through and process it as part of the pool.
4441 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4443 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4445 session
[i
].ip_pool_index
= ipid
;
4449 ip_address_pool
[ipid
].assigned
= 1;
4450 ip_address_pool
[ipid
].session
= i
;
4451 ip_address_pool
[ipid
].last
= time_now
;
4452 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4453 session
[i
].ip_pool_index
= ipid
;
4454 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4459 // Fix the address pool to match a changed session.
4460 // (usually when the master sends us an update).
4461 static void fix_address_pool(int sid
)
4465 ipid
= session
[sid
].ip_pool_index
;
4467 if (ipid
> ip_pool_size
)
4468 return; // Ignore it. rebuild_address_pool will fix it up.
4470 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4471 return; // Just ignore it. rebuild_address_pool will take care of it.
4473 ip_address_pool
[ipid
].assigned
= 1;
4474 ip_address_pool
[ipid
].session
= sid
;
4475 ip_address_pool
[ipid
].last
= time_now
;
4476 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4480 // Add a block of addresses to the IP pool to hand out.
4482 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4486 prefixlen
= 32; // Host route only.
4488 addr
&= 0xffffffff << (32 - prefixlen
);
4490 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4493 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4495 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4496 continue; // Skip 0 and broadcast addresses.
4498 ip_address_pool
[ip_pool_size
].address
= i
;
4499 ip_address_pool
[ip_pool_size
].assigned
= 0;
4501 if (ip_pool_size
>= MAXIPPOOL
)
4503 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4509 // Initialize the IP address pool
4510 static void initippool()
4515 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4517 if (!(f
= fopen(IPPOOLFILE
, "r")))
4519 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4523 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4526 buf
[4095] = 0; // Force it to be zero terminated/
4528 if (*buf
== '#' || *buf
== '\n')
4529 continue; // Skip comments / blank lines
4530 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4531 if ((p
= (char *)strchr(buf
, ':')))
4535 src
= inet_addr(buf
);
4536 if (src
== INADDR_NONE
)
4538 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4541 // This entry is for a specific IP only
4542 if (src
!= config
->bind_address
)
4547 if ((p
= (char *)strchr(pool
, '/')))
4551 in_addr_t start
= 0;
4553 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4555 if (!*p
|| !(numbits
= atoi(p
)))
4557 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4560 start
= ntohl(inet_addr(pool
));
4562 // Add a static route for this pool
4563 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4564 fmtaddr(htonl(start
), 0), numbits
);
4566 routeset(0, start
, numbits
, 0, 1);
4568 add_to_ip_pool(start
, numbits
);
4572 // It's a single ip address
4573 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4577 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4580 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4582 struct sockaddr_in snoop_addr
= {0};
4583 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4586 snoop_addr
.sin_family
= AF_INET
;
4587 snoop_addr
.sin_addr
.s_addr
= destination
;
4588 snoop_addr
.sin_port
= ntohs(port
);
4590 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4591 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4592 htons(snoop_addr
.sin_port
));
4594 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4595 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4597 STAT(packets_snooped
);
4600 static int dump_session(FILE **f
, sessiont
*s
)
4602 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4607 char filename
[1024];
4609 time_t now
= time(NULL
);
4611 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4612 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4614 if (!(*f
= fopen(filename
, "w")))
4616 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4620 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4621 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4626 "# format: username ip qos uptxoctets downrxoctets\n",
4628 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4633 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4634 fprintf(*f
, "%s %s %d %u %u\n",
4635 s
->user
, // username
4636 fmtaddr(htonl(s
->ip
), 0), // ip
4637 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4638 (uint32_t) s
->cin_delta
, // uptxoctets
4639 (uint32_t) s
->cout_delta
); // downrxoctets
4641 s
->cin_delta
= s
->cout_delta
= 0;
4646 static void dump_acct_info(int all
)
4652 CSTAT(dump_acct_info
);
4656 for (i
= 0; i
< shut_acct_n
; i
++)
4657 dump_session(&f
, &shut_acct
[i
]);
4663 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4664 dump_session(&f
, &session
[i
]);
4671 int main(int argc
, char *argv
[])
4675 char *optconfig
= CONFIGFILE
;
4677 time(&basetime
); // start clock
4680 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4685 if (fork()) exit(0);
4687 freopen("/dev/null", "r", stdin
);
4688 freopen("/dev/null", "w", stdout
);
4689 freopen("/dev/null", "w", stderr
);
4698 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4701 printf("Args are:\n"
4702 "\t-d\t\tDetach from terminal\n"
4703 "\t-c <file>\tConfig file\n"
4704 "\t-h <hostname>\tForce hostname\n"
4712 // Start the timer routine off
4714 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4717 initdata(optdebug
, optconfig
);
4722 init_tbf(config
->num_tbfs
);
4724 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4725 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4726 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4729 rlim
.rlim_cur
= RLIM_INFINITY
;
4730 rlim
.rlim_max
= RLIM_INFINITY
;
4731 // Remove the maximum core size
4732 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4733 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4735 // Make core dumps go to /tmp
4739 if (config
->scheduler_fifo
)
4742 struct sched_param params
= {0};
4743 params
.sched_priority
= 1;
4745 if (get_nprocs() < 2)
4747 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4748 config
->scheduler_fifo
= 0;
4752 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4754 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4758 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4759 config
->scheduler_fifo
= 0;
4766 /* Set up the cluster communications port. */
4767 if (cluster_init() < 0)
4771 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4779 unsigned seed
= time_now
^ getpid();
4780 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4784 signal(SIGHUP
, sighup_handler
);
4785 signal(SIGCHLD
, sigchild_handler
);
4786 signal(SIGTERM
, shutdown_handler
);
4787 signal(SIGINT
, shutdown_handler
);
4788 signal(SIGQUIT
, shutdown_handler
);
4790 // Prevent us from getting paged out
4791 if (config
->lock_pages
)
4793 if (!mlockall(MCL_CURRENT
))
4794 LOG(1, 0, 0, "Locking pages into memory\n");
4796 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4801 /* remove plugins (so cleanup code gets run) */
4804 // Remove the PID file if we wrote it
4805 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4806 unlink(config
->pid_file
);
4808 /* kill CLI children */
4809 signal(SIGTERM
, SIG_IGN
);
4814 static void sighup_handler(int sig
)
4819 static void shutdown_handler(int sig
)
4821 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4824 static void sigchild_handler(int sig
)
4826 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4830 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4833 *challenge_response
= NULL
;
4835 if (!*config
->l2tp_secret
)
4837 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4841 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4843 *challenge_response
= calloc(17, 1);
4846 MD5_Update(&ctx
, &id
, 1);
4847 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4848 MD5_Update(&ctx
, challenge
, challenge_length
);
4849 MD5_Final(*challenge_response
, &ctx
);
4854 static int facility_value(char *name
)
4857 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4859 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4860 return facilitynames
[i
].c_val
;
4865 static void update_config()
4869 static int timeout
= 0;
4870 static int interval
= 0;
4877 if (log_stream
!= stderr
)
4883 if (*config
->log_filename
)
4885 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4887 char *p
= config
->log_filename
+ 7;
4890 openlog("l2tpns", LOG_PID
, facility_value(p
));
4894 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4896 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4898 fseek(log_stream
, 0, SEEK_END
);
4899 setbuf(log_stream
, NULL
);
4903 log_stream
= stderr
;
4904 setbuf(log_stream
, NULL
);
4910 log_stream
= stderr
;
4911 setbuf(log_stream
, NULL
);
4914 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4915 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4917 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4918 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4919 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4921 // reset MRU/MSS globals
4922 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4923 if (MRU
> PPPoE_MRU
)
4926 MSS
= MRU
- TCP_HDRS
;
4929 config
->numradiusservers
= 0;
4930 for (i
= 0; i
< MAXRADSERVER
; i
++)
4931 if (config
->radiusserver
[i
])
4933 config
->numradiusservers
++;
4934 // Set radius port: if not set, take the port from the
4935 // first radius server. For the first radius server,
4936 // take the #defined default value from l2tpns.h
4938 // test twice, In case someone works with
4939 // a secondary radius server without defining
4940 // a primary one, this will work even then.
4941 if (i
> 0 && !config
->radiusport
[i
])
4942 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4943 if (!config
->radiusport
[i
])
4944 config
->radiusport
[i
] = RADPORT
;
4947 if (!config
->numradiusservers
)
4948 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4950 // parse radius_authtypes_s
4951 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4952 p
= config
->radius_authtypes_s
;
4955 char *s
= strpbrk(p
, " \t,");
4961 while (*s
== ' ' || *s
== '\t')
4968 if (!strncasecmp("chap", p
, strlen(p
)))
4970 else if (!strncasecmp("pap", p
, strlen(p
)))
4973 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4975 config
->radius_authtypes
|= type
;
4976 if (!config
->radius_authprefer
)
4977 config
->radius_authprefer
= type
;
4982 if (!config
->radius_authtypes
)
4984 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4985 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4988 // normalise radius_authtypes_s
4989 if (config
->radius_authprefer
== AUTHPAP
)
4991 strcpy(config
->radius_authtypes_s
, "pap");
4992 if (config
->radius_authtypes
& AUTHCHAP
)
4993 strcat(config
->radius_authtypes_s
, ", chap");
4997 strcpy(config
->radius_authtypes_s
, "chap");
4998 if (config
->radius_authtypes
& AUTHPAP
)
4999 strcat(config
->radius_authtypes_s
, ", pap");
5002 if (!config
->radius_dae_port
)
5003 config
->radius_dae_port
= DAEPORT
;
5005 // re-initialise the random number source
5006 initrandom(config
->random_device
);
5009 for (i
= 0; i
< MAXPLUGINS
; i
++)
5011 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5014 if (*config
->plugins
[i
])
5017 add_plugin(config
->plugins
[i
]);
5019 else if (*config
->old_plugins
[i
])
5022 remove_plugin(config
->old_plugins
[i
]);
5027 guest_accounts_num
= 0;
5028 char *p2
= config
->guest_user
;
5031 char *s
= strpbrk(p2
, " \t,");
5035 while (*s
== ' ' || *s
== '\t')
5042 strcpy(guest_users
[guest_accounts_num
], p2
);
5043 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5044 guest_accounts_num
++;
5047 // Rebuild the guest_user array
5048 strcpy(config
->guest_user
, "");
5050 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5052 strcat(config
->guest_user
, guest_users
[ui
]);
5053 if (ui
<guest_accounts_num
-1)
5055 strcat(config
->guest_user
, ",");
5060 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5061 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5062 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5063 if (!*config
->cluster_interface
)
5064 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5066 if (!config
->cluster_hb_interval
)
5067 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5069 if (!config
->cluster_hb_timeout
)
5070 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5072 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5074 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5075 // late, ensure we're sufficiently larger than that
5076 int t
= 4 * config
->cluster_hb_interval
+ 11;
5078 if (config
->cluster_hb_timeout
< t
)
5080 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5081 config
->cluster_hb_timeout
= t
;
5084 // Push timing changes to the slaves immediately if we're the master
5085 if (config
->cluster_iam_master
)
5086 cluster_heartbeat();
5088 interval
= config
->cluster_hb_interval
;
5089 timeout
= config
->cluster_hb_timeout
;
5093 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5096 if ((f
= fopen(config
->pid_file
, "w")))
5098 fprintf(f
, "%d\n", getpid());
5100 config
->wrote_pid
= 1;
5104 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5109 static void read_config_file()
5113 if (!config
->config_file
) return;
5114 if (!(f
= fopen(config
->config_file
, "r")))
5116 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5120 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5122 LOG(3, 0, 0, "Done reading config file\n");
5126 int sessionsetup(sessionidt s
, tunnelidt t
)
5128 // A session now exists, set it up
5134 CSTAT(sessionsetup
);
5136 LOG(3, s
, t
, "Doing session setup for session\n");
5138 // Join a bundle if the MRRU option is accepted
5139 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5141 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5142 if (join_bundle(s
) > 0)
5143 cluster_send_bundle(session
[s
].bundle
);
5146 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5147 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5154 assign_ip_address(s
);
5157 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5158 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5161 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5162 fmtaddr(htonl(session
[s
].ip
), 0));
5166 // Make sure this is right
5167 session
[s
].tunnel
= t
;
5169 // zap old sessions with same IP and/or username
5170 // Don't kill gardened sessions - doing so leads to a DoS
5171 // from someone who doesn't need to know the password
5174 user
= session
[s
].user
;
5175 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5177 if (i
== s
) continue;
5178 if (!session
[s
].opened
) continue;
5179 // Allow duplicate sessions for multilink ones of the same bundle.
5180 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5182 if (ip
== session
[i
].ip
)
5184 sessionkill(i
, "Duplicate IP address");
5188 if (config
->allow_duplicate_users
) continue;
5189 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5193 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5195 if (!strcasecmp(user
, guest_users
[gu
]))
5201 if (found
) continue;
5203 // Drop the new session in case of duplicate sessionss, not the old one.
5204 if (!strcasecmp(user
, session
[i
].user
))
5205 sessionkill(i
, "Duplicate session for users");
5209 // no need to set a route for the same IP address of the bundle
5210 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5214 // Add the route for this session.
5215 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5217 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5218 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5221 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5224 // Static IPs need to be routed if not already
5225 // convered by a Framed-Route. Anything else is part
5226 // of the IP address pool and is already routed, it
5227 // just needs to be added to the IP cache.
5228 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5229 if (session
[s
].ip_pool_index
== -1) // static ip
5231 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5234 cache_ipmap(session
[s
].ip
, s
);
5237 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5238 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5240 // Run the plugin's against this new session.
5242 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5243 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5246 // Allocate TBFs if throttled
5247 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5248 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5250 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5252 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5253 fmtaddr(htonl(session
[s
].ip
), 0),
5254 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5256 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5258 return 1; // RADIUS OK and IP allocated, done...
5262 // This session just got dropped on us by the master or something.
5263 // Make sure our tables up up to date...
5265 int load_session(sessionidt s
, sessiont
*new)
5271 if (new->ip_pool_index
>= MAXIPPOOL
||
5272 new->tunnel
>= MAXTUNNEL
)
5274 LOG(0, s
, 0, "Strange session update received!\n");
5275 // FIXME! What to do here?
5280 // Ok. All sanity checks passed. Now we're committed to
5281 // loading the new session.
5284 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5286 // See if routes/ip cache need updating
5287 if (new->ip
!= session
[s
].ip
)
5290 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5291 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5292 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5300 // remove old routes...
5301 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5303 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5304 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5307 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5313 if (session
[s
].ip_pool_index
== -1) // static IP
5315 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5317 else // It's part of the IP pool, remove it manually.
5318 uncache_ipmap(session
[s
].ip
);
5323 // add new routes...
5324 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5326 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5327 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5330 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5336 // If there's a new one, add it.
5337 if (new->ip_pool_index
== -1)
5339 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5342 cache_ipmap(new->ip
, s
);
5347 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5348 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5351 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5353 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5357 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5359 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5360 new->filter_out
= 0;
5363 if (new->filter_in
!= session
[s
].filter_in
)
5365 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5366 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5369 if (new->filter_out
!= session
[s
].filter_out
)
5371 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5372 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5375 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5376 // for walking the sessions to forward byte counts to the master.
5377 config
->cluster_highest_sessionid
= s
;
5379 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5381 // Do fixups into address pool.
5382 if (new->ip_pool_index
!= -1)
5383 fix_address_pool(s
);
5388 static void initplugins()
5392 loaded_plugins
= ll_init();
5393 // Initialize the plugins to nothing
5394 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5395 plugins
[i
] = ll_init();
5398 static void *open_plugin(char *plugin_name
, int load
)
5400 char path
[256] = "";
5402 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5403 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5404 return dlopen(path
, RTLD_NOW
);
5407 // plugin callback to get a config value
5408 static void *getconfig(char *key
, enum config_typet type
)
5412 for (i
= 0; config_values
[i
].key
; i
++)
5414 if (!strcmp(config_values
[i
].key
, key
))
5416 if (config_values
[i
].type
== type
)
5417 return ((void *) config
) + config_values
[i
].offset
;
5419 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5420 key
, type
, config_values
[i
].type
);
5426 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5430 static int add_plugin(char *plugin_name
)
5432 static struct pluginfuncs funcs
= {
5437 sessiontbysessionidt
,
5438 sessionidtbysessiont
,
5445 cluster_send_session
,
5448 void *p
= open_plugin(plugin_name
, 1);
5449 int (*initfunc
)(struct pluginfuncs
*);
5454 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5458 if (ll_contains(loaded_plugins
, p
))
5461 return 0; // already loaded
5465 int *v
= dlsym(p
, "plugin_api_version");
5466 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5468 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5474 if ((initfunc
= dlsym(p
, "plugin_init")))
5476 if (!initfunc(&funcs
))
5478 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5484 ll_push(loaded_plugins
, p
);
5486 for (i
= 0; i
< max_plugin_functions
; i
++)
5489 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5491 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5492 ll_push(plugins
[i
], x
);
5496 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5500 static void run_plugin_done(void *plugin
)
5502 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5508 static int remove_plugin(char *plugin_name
)
5510 void *p
= open_plugin(plugin_name
, 0);
5516 if (ll_contains(loaded_plugins
, p
))
5519 for (i
= 0; i
< max_plugin_functions
; i
++)
5522 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5523 ll_delete(plugins
[i
], x
);
5526 ll_delete(loaded_plugins
, p
);
5532 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5536 int run_plugins(int plugin_type
, void *data
)
5538 int (*func
)(void *data
);
5540 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5541 return PLUGIN_RET_ERROR
;
5543 ll_reset(plugins
[plugin_type
]);
5544 while ((func
= ll_next(plugins
[plugin_type
])))
5548 if (r
!= PLUGIN_RET_OK
)
5549 return r
; // stop here
5552 return PLUGIN_RET_OK
;
5555 static void plugins_done()
5559 ll_reset(loaded_plugins
);
5560 while ((p
= ll_next(loaded_plugins
)))
5564 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5566 struct nsctl request
;
5567 struct nsctl response
;
5568 int type
= unpack_control(&request
, buf
, len
);
5572 if (log_stream
&& config
->debug
>= 4)
5576 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5577 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5581 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5582 dump_control(&request
, log_stream
);
5588 case NSCTL_REQ_LOAD
:
5589 if (request
.argc
!= 1)
5591 response
.type
= NSCTL_RES_ERR
;
5593 response
.argv
[0] = "name of plugin required";
5595 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5597 response
.type
= NSCTL_RES_ERR
;
5599 response
.argv
[0] = !r
5600 ? "plugin already loaded"
5601 : "error loading plugin";
5605 response
.type
= NSCTL_RES_OK
;
5611 case NSCTL_REQ_UNLOAD
:
5612 if (request
.argc
!= 1)
5614 response
.type
= NSCTL_RES_ERR
;
5616 response
.argv
[0] = "name of plugin required";
5618 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5620 response
.type
= NSCTL_RES_ERR
;
5622 response
.argv
[0] = !r
5623 ? "plugin not loaded"
5624 : "plugin not found";
5628 response
.type
= NSCTL_RES_OK
;
5634 case NSCTL_REQ_HELP
:
5635 response
.type
= NSCTL_RES_OK
;
5638 ll_reset(loaded_plugins
);
5639 while ((p
= ll_next(loaded_plugins
)))
5641 char **help
= dlsym(p
, "plugin_control_help");
5642 while (response
.argc
< 0xff && help
&& *help
)
5643 response
.argv
[response
.argc
++] = *help
++;
5648 case NSCTL_REQ_CONTROL
:
5650 struct param_control param
= {
5651 config
->cluster_iam_master
,
5658 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5660 if (r
== PLUGIN_RET_ERROR
)
5662 response
.type
= NSCTL_RES_ERR
;
5664 response
.argv
[0] = param
.additional
5666 : "error returned by plugin";
5668 else if (r
== PLUGIN_RET_NOTMASTER
)
5670 static char msg
[] = "must be run on master: 000.000.000.000";
5672 response
.type
= NSCTL_RES_ERR
;
5674 if (config
->cluster_master_address
)
5676 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5677 response
.argv
[0] = msg
;
5681 response
.argv
[0] = "must be run on master: none elected";
5684 else if (!(param
.response
& NSCTL_RESPONSE
))
5686 response
.type
= NSCTL_RES_ERR
;
5688 response
.argv
[0] = param
.response
5689 ? "unrecognised response value from plugin"
5690 : "unhandled action";
5694 response
.type
= param
.response
;
5696 if (param
.additional
)
5699 response
.argv
[0] = param
.additional
;
5707 response
.type
= NSCTL_RES_ERR
;
5709 response
.argv
[0] = "error unpacking control packet";
5712 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5715 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5719 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5722 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5723 if (log_stream
&& config
->debug
>= 4)
5725 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5726 dump_control(&response
, log_stream
);
5730 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5731 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5736 static tunnelidt
new_tunnel()
5739 for (i
= 1; i
< MAXTUNNEL
; i
++)
5741 if (tunnel
[i
].state
== TUNNELFREE
)
5743 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5744 if (i
> config
->cluster_highest_tunnelid
)
5745 config
->cluster_highest_tunnelid
= i
;
5749 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5754 // We're becoming the master. Do any required setup..
5756 // This is principally telling all the plugins that we're
5757 // now a master, and telling them about all the sessions
5758 // that are active too..
5760 void become_master(void)
5763 static struct event_data d
[RADIUS_FDS
];
5764 struct epoll_event e
;
5766 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5768 // running a bunch of iptables commands is slow and can cause
5769 // the master to drop tunnels on takeover--kludge around the
5770 // problem by forking for the moment (note: race)
5771 if (!fork_and_close())
5773 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5775 if (!session
[s
].opened
) // Not an in-use session.
5778 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5785 for (i
= 0; i
< RADIUS_FDS
; i
++)
5787 d
[i
].type
= FD_TYPE_RADIUS
;
5791 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5795 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5801 if (CLI_HELP_REQUESTED
)
5802 return CLI_HELP_NO_ARGS
;
5805 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5807 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5810 if (!session
[s
].opened
)
5813 idle
= time_now
- session
[s
].last_data
;
5814 idle
/= 5 ; // In multiples of 5 seconds.
5824 for (i
= 0; i
< 63; ++i
)
5826 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5828 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5829 cli_print(cli
, "%d total sessions open.", count
);
5833 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5839 if (CLI_HELP_REQUESTED
)
5840 return CLI_HELP_NO_ARGS
;
5843 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5845 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5848 if (!session
[s
].opened
)
5851 d
= time_now
- session
[s
].opened
;
5854 while (d
> 1 && open
< 32)
5864 for (i
= 0; i
< 30; ++i
)
5866 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5869 cli_print(cli
, "%d total sessions open.", count
);
5875 * This unencodes the AVP using the L2TP secret and the previously
5876 * stored random vector. It overwrites the hidden data with the
5877 * unhidden AVP subformat.
5879 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5885 uint16_t m
= htons(type
);
5887 // Compute initial pad
5889 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5890 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5891 MD5_Update(&ctx
, vector
, vec_len
);
5892 MD5_Final(digest
, &ctx
);
5894 // pointer to last decoded 16 octets
5899 // calculate a new pad based on the last decoded block
5900 if (d
>= sizeof(digest
))
5903 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5904 MD5_Update(&ctx
, last
, sizeof(digest
));
5905 MD5_Final(digest
, &ctx
);
5911 *value
++ ^= digest
[d
++];
5916 int find_filter(char const *name
, size_t len
)
5921 for (i
= 0; i
< MAXFILTER
; i
++)
5923 if (!*ip_filters
[i
].name
)
5931 if (strlen(ip_filters
[i
].name
) != len
)
5934 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5941 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5945 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5946 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5947 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5948 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5949 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5955 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5959 case FILTER_FLAG_OP_ANY
:
5960 return (flags
& sflags
) || (~flags
& cflags
);
5962 case FILTER_FLAG_OP_ALL
:
5963 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5965 case FILTER_FLAG_OP_EST
:
5966 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5972 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5974 uint16_t frag_offset
;
5978 uint16_t src_port
= 0;
5979 uint16_t dst_port
= 0;
5981 ip_filter_rulet
*rule
;
5983 if (len
< 20) // up to end of destination address
5986 if ((*buf
>> 4) != 4) // IPv4
5989 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5991 src_ip
= *(in_addr_t
*) (buf
+ 12);
5992 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5994 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5996 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5997 if (len
< l
+ 4) // ports
6000 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6001 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6002 if (proto
== IPPROTO_TCP
)
6004 if (len
< l
+ 14) // flags
6007 flags
= buf
[l
+ 13] & 0x3f;
6011 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6013 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6016 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6017 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6020 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6021 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6026 // layer 4 deny rules are skipped
6027 if (rule
->action
== FILTER_ACTION_DENY
&&
6028 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6036 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6038 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6041 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6044 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6045 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6052 return rule
->action
== FILTER_ACTION_PERMIT
;