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
[MAXHOSTNAME
] = ""; // 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
),
162 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
163 CONFIG("hostname", hostname
, STRING
),
164 CONFIG("nexthop_address", nexthop_address
, IPv4
),
165 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
169 static char *plugin_functions
[] = {
174 "plugin_new_session",
175 "plugin_kill_session",
177 "plugin_radius_response",
178 "plugin_radius_reset",
179 "plugin_radius_account",
180 "plugin_become_master",
181 "plugin_new_session_master",
184 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
186 // Counters for shutdown sessions
187 static sessiont shut_acct
[8192];
188 static sessionidt shut_acct_n
= 0;
190 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
191 bundlet
*bundle
= NULL
; // Array of bundle structures.
192 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
193 sessiont
*session
= NULL
; // Array of session structures.
194 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
195 radiust
*radius
= NULL
; // Array of radius structures.
196 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
197 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
198 static controlt
*controlfree
= 0;
199 struct Tstats
*_statistics
= NULL
;
201 struct Tringbuffer
*ringbuffer
= NULL
;
204 static ssize_t
netlink_send(struct nlmsghdr
*nh
);
205 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
);
206 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
207 static void uncache_ipmap(in_addr_t ip
);
208 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
209 static void free_ip_address(sessionidt s
);
210 static void dump_acct_info(int all
);
211 static void sighup_handler(int sig
);
212 static void shutdown_handler(int sig
);
213 static void sigchild_handler(int sig
);
214 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
215 static void update_config(void);
216 static void read_config_file(void);
217 static void initplugins(void);
218 static int add_plugin(char *plugin_name
);
219 static int remove_plugin(char *plugin_name
);
220 static void plugins_done(void);
221 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
222 static tunnelidt
new_tunnel(void);
223 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
224 static void bundleclear(bundleidt b
);
226 // on slaves, alow BGP to withdraw cleanly before exiting
229 // quit actions (master)
230 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
231 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
233 // return internal time (10ths since process startup), set f if given
234 // as a side-effect sets time_now, and time_changed
235 static clockt
now(double *f
)
239 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
240 if (t
.tv_sec
!= time_now
)
245 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
248 // work out a retry time based on try number
249 // This is a straight bounded exponential backoff.
250 // Maximum re-try time is 32 seconds. (2^5).
251 clockt
backoff(uint8_t try)
253 if (try > 5) try = 5; // max backoff
254 return now(NULL
) + 10 * (1 << try);
259 // Log a debug message. Typically called via the LOG macro
261 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
263 static char message
[65536] = {0};
269 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
270 ringbuffer
->tail
= 0;
271 if (ringbuffer
->tail
== ringbuffer
->head
)
272 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
273 ringbuffer
->head
= 0;
275 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
276 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
277 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
278 va_start(ap
, format
);
279 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
284 if (config
->debug
< level
) return;
286 va_start(ap
, format
);
287 vsnprintf(message
, sizeof(message
), format
, ap
);
290 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
292 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
297 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
300 const uint8_t *d
= data
;
302 if (config
->debug
< level
) return;
304 // No support for _log_hex to syslog
307 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
308 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
310 for (i
= 0; i
< maxsize
; )
312 fprintf(log_stream
, "%4X: ", i
);
313 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
315 fprintf(log_stream
, "%02X ", d
[j
]);
317 fputs(": ", log_stream
);
320 for (; j
< i
+ 16; j
++)
322 fputs(" ", log_stream
);
324 fputs(": ", log_stream
);
327 fputs(" ", log_stream
);
328 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
330 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
331 fputc(d
[j
], log_stream
);
333 fputc('.', log_stream
);
336 fputs(" ", log_stream
);
340 fputs("\n", log_stream
);
344 setbuf(log_stream
, NULL
);
348 // update a counter, accumulating 2^32 wraps
349 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
351 uint32_t new = *counter
+ delta
;
358 // initialise the random generator
359 static void initrandom(char *source
)
361 static char path
[sizeof(config
->random_device
)] = "*undefined*";
363 // reinitialise only if we are forced to do so or if the config has changed
364 if (source
&& !strncmp(path
, source
, sizeof(path
)))
367 // close previous source, if any
376 snprintf(path
, sizeof(path
), "%s", source
);
380 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
382 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
383 path
, strerror(errno
));
388 // fill buffer with random data
389 void random_data(uint8_t *buf
, int len
)
396 n
= read(rand_fd
, buf
, len
);
397 if (n
>= len
) return;
402 LOG(0, 0, 0, "Error reading from random source: %s\n",
405 // fall back to rand()
413 // append missing data
415 // not using the low order bits from the prng stream
416 buf
[n
++] = (rand() >> 4) & 0xff;
421 // This adds it to the routing table, advertises it
422 // via BGP if enabled, and stuffs it into the
423 // 'sessionbyip' cache.
425 // 'ip' must be in _host_ order.
427 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
437 if (!prefixlen
) prefixlen
= 32;
439 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
441 memset(&req
, 0, sizeof(req
));
445 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
446 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
449 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
450 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
452 req
.rt
.rtm_family
= AF_INET
;
453 req
.rt
.rtm_dst_len
= prefixlen
;
454 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
455 req
.rt
.rtm_protocol
= RTPROT_BOOT
; // XXX
456 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
457 req
.rt
.rtm_type
= RTN_UNICAST
;
459 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
461 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
465 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
468 LOG(1, s
, 0, "Route %s %s/%d%s%s\n", add
? "add" : "del",
469 fmtaddr(htonl(ip
), 0), prefixlen
,
470 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
472 if (netlink_send(&req
.nh
) < 0)
473 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
477 bgp_add_route(htonl(ip
), prefixlen
);
479 bgp_del_route(htonl(ip
), prefixlen
);
482 // Add/Remove the IPs to the 'sessionbyip' cache.
483 // Note that we add the zero address in the case of
484 // a network route. Roll on CIDR.
486 // Note that 's == 0' implies this is the address pool.
487 // We still cache it here, because it will pre-fill
488 // the malloc'ed tree.
492 if (!add
) // Are we deleting a route?
493 s
= 0; // Caching the session as '0' is the same as uncaching.
495 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
500 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
508 char ipv6addr
[INET6_ADDRSTRLEN
];
510 if (!config
->ipv6_prefix
.s6_addr
[0])
512 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
516 memset(&req
, 0, sizeof(req
));
520 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
521 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
524 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
525 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
527 req
.rt
.rtm_family
= AF_INET6
;
528 req
.rt
.rtm_dst_len
= prefixlen
;
529 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
530 req
.rt
.rtm_protocol
= RTPROT_BOOT
; // XXX
531 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
532 req
.rt
.rtm_type
= RTN_UNICAST
;
534 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
535 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
537 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
539 LOG(1, 0, 0, "Route %s %s/%d\n",
541 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
544 if (netlink_send(&req
.nh
) < 0)
545 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
549 bgp_add_route6(ip
, prefixlen
);
551 bgp_del_route6(ip
, prefixlen
);
556 if (!add
) // Are we deleting a route?
557 s
= 0; // Caching the session as '0' is the same as uncaching.
559 cache_ipv6map(ip
, prefixlen
, s
);
566 // Set up netlink socket
567 static void initnetlink(void)
569 struct sockaddr_nl nladdr
;
571 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
574 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
578 memset(&nladdr
, 0, sizeof(nladdr
));
579 nladdr
.nl_family
= AF_NETLINK
;
580 nladdr
.nl_pid
= getpid();
582 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
584 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
589 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
591 struct sockaddr_nl nladdr
;
595 nh
->nlmsg_pid
= getpid();
596 nh
->nlmsg_seq
= ++nlseqnum
;
598 // set kernel address
599 memset(&nladdr
, 0, sizeof(nladdr
));
600 nladdr
.nl_family
= AF_NETLINK
;
602 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
603 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
605 return sendmsg(nlfd
, &msg
, 0);
608 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
610 struct sockaddr_nl nladdr
;
614 // set kernel address
615 memset(&nladdr
, 0, sizeof(nladdr
));
616 nladdr
.nl_family
= AF_NETLINK
;
618 iov
= (struct iovec
){ buf
, len
};
619 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
621 return recvmsg(nlfd
, &msg
, 0);
624 /* adapted from iproute2 */
625 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
627 int len
= RTA_LENGTH(alen
);
630 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
631 rta
->rta_type
= type
;
633 memcpy(RTA_DATA(rta
), data
, alen
);
634 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
637 // messages corresponding to different phases seq number
638 static char *tun_nl_phase_msg
[] = {
640 "getting tun interface index",
641 "setting tun interface parameters",
642 "setting tun IPv4 address",
643 "setting tun LL IPv6 address",
644 "setting tun global IPv6 address",
648 // Set up TUN interface
649 static void inittun(void)
653 memset(&ifr
, 0, sizeof(ifr
));
654 ifr
.ifr_flags
= IFF_TUN
;
656 tunfd
= open(TUNDEVICE
, O_RDWR
);
659 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
663 int flags
= fcntl(tunfd
, F_GETFL
, 0);
664 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
666 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
668 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
671 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
) - 1);
672 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
));
674 tunidx
= if_nametoindex(config
->tundevice
);
677 LOG(0, 0, 0, "Can't get tun interface index\n");
686 struct ifinfomsg ifinfo
;
687 struct ifaddrmsg ifaddr
;
689 char rtdata
[32]; // 32 should be enough
691 uint32_t txqlen
, mtu
;
694 memset(&req
, 0, sizeof(req
));
696 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
697 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
698 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
700 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
701 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
702 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
703 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
705 /* Bump up the qlen to deal with bursts from the network */
707 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
708 /* set MTU to modem MRU */
710 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
712 if (netlink_send(&req
.nh
) < 0)
715 memset(&req
, 0, sizeof(req
));
717 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
718 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
719 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
721 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
722 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
723 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
724 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
726 if (config
->bind_address
)
727 ip
= config
->bind_address
;
729 ip
= 0x01010101; // 1.1.1.1
730 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
732 if (netlink_send(&req
.nh
) < 0)
735 // Only setup IPv6 on the tun device if we have a configured prefix
736 if (config
->ipv6_prefix
.s6_addr
[0]) {
739 memset(&req
, 0, sizeof(req
));
741 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
742 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
743 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
745 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
746 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
747 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
748 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
750 // Link local address is FE80::1
751 memset(&ip6
, 0, sizeof(ip6
));
752 ip6
.s6_addr
[0] = 0xFE;
753 ip6
.s6_addr
[1] = 0x80;
755 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
757 if (netlink_send(&req
.nh
) < 0)
760 memset(&req
, 0, sizeof(req
));
762 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
763 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
764 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
766 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
767 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
768 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
769 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
771 // Global address is prefix::1
772 ip6
= config
->ipv6_prefix
;
774 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
776 if (netlink_send(&req
.nh
) < 0)
780 memset(&req
, 0, sizeof(req
));
782 req
.nh
.nlmsg_type
= NLMSG_DONE
;
783 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
785 if (netlink_send(&req
.nh
) < 0)
788 // if we get an error for seqnum < min_initok_nlseqnum,
789 // we must exit as initialization went wrong
790 if (config
->ipv6_prefix
.s6_addr
[0])
791 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
793 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
799 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
804 static void initudp(void)
807 struct sockaddr_in addr
;
810 memset(&addr
, 0, sizeof(addr
));
811 addr
.sin_family
= AF_INET
;
812 addr
.sin_port
= htons(L2TPPORT
);
813 addr
.sin_addr
.s_addr
= config
->bind_address
;
814 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
815 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
817 int flags
= fcntl(udpfd
, F_GETFL
, 0);
818 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
820 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
822 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
827 memset(&addr
, 0, sizeof(addr
));
828 addr
.sin_family
= AF_INET
;
829 addr
.sin_port
= htons(NSCTL_PORT
);
830 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
831 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
832 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
833 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
835 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
839 // Dynamic Authorization Extensions to RADIUS
840 memset(&addr
, 0, sizeof(addr
));
841 addr
.sin_family
= AF_INET
;
842 addr
.sin_port
= htons(config
->radius_dae_port
);
843 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
844 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
845 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
846 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
848 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
853 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
857 // Find session by IP, < 1 for not found
859 // Confusingly enough, this 'ip' must be
860 // in _network_ order. This being the common
861 // case when looking it up from IP packet headers.
863 // We actually use this cache for two things.
864 // #1. For used IP addresses, this maps to the
865 // session ID that it's used by.
866 // #2. For un-used IP addresses, this maps to the
867 // index into the pool table that contains that
871 static sessionidt
lookup_ipmap(in_addr_t ip
)
873 uint8_t *a
= (uint8_t *) &ip
;
874 union iphash
*h
= ip_hash
;
876 if (!(h
= h
[*a
++].idx
)) return 0;
877 if (!(h
= h
[*a
++].idx
)) return 0;
878 if (!(h
= h
[*a
++].idx
)) return 0;
883 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
885 struct ipv6radix
*curnode
;
888 char ipv6addr
[INET6_ADDRSTRLEN
];
890 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
894 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
896 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
901 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
902 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
909 sessionidt
sessionbyip(in_addr_t ip
)
911 sessionidt s
= lookup_ipmap(ip
);
914 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
920 sessionidt
sessionbyipv6(struct in6_addr ip
)
923 CSTAT(sessionbyipv6
);
925 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
926 (ip
.s6_addr
[0] == 0xFE &&
927 ip
.s6_addr
[1] == 0x80 &&
928 ip
.s6_addr16
[1] == 0 &&
929 ip
.s6_addr16
[2] == 0 &&
930 ip
.s6_addr16
[3] == 0)) {
931 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
933 s
= lookup_ipv6map(ip
);
936 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
943 // Take an IP address in HOST byte order and
944 // add it to the sessionid by IP cache.
946 // (It's actually cached in network order)
948 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
950 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
951 uint8_t *a
= (uint8_t *) &nip
;
952 union iphash
*h
= ip_hash
;
955 for (i
= 0; i
< 3; i
++)
957 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
966 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
969 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
970 // else a map to an ip pool index.
973 static void uncache_ipmap(in_addr_t ip
)
975 cache_ipmap(ip
, 0); // Assign it to the NULL session.
978 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
982 struct ipv6radix
*curnode
;
983 char ipv6addr
[INET6_ADDRSTRLEN
];
985 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
987 bytes
= prefixlen
>> 3;
990 if (curnode
->branch
== NULL
)
992 if (!(curnode
->branch
= calloc(256,
993 sizeof (struct ipv6radix
))))
996 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1003 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1004 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1008 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1009 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1015 // CLI list to dump current ipcache.
1017 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1019 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1023 if (CLI_HELP_REQUESTED
)
1024 return CLI_HELP_NO_ARGS
;
1026 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1028 for (i
= 0; i
< 256; ++i
)
1034 for (j
= 0; j
< 256; ++j
)
1040 for (k
= 0; k
< 256; ++k
)
1046 for (l
= 0; l
< 256; ++l
)
1051 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1057 cli_print(cli
, "%d entries in cache", count
);
1062 // Find session by username, 0 for not found
1063 // walled garden users aren't authenticated, so the username is
1064 // reasonably useless. Ignore them to avoid incorrect actions
1066 // This is VERY inefficent. Don't call it often. :)
1068 sessionidt
sessionbyuser(char *username
)
1071 CSTAT(sessionbyuser
);
1073 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1075 if (!session
[s
].opened
)
1078 if (session
[s
].walled_garden
)
1079 continue; // Skip walled garden users.
1081 if (!strncmp(session
[s
].user
, username
, 128))
1085 return 0; // Not found.
1088 void send_garp(in_addr_t ip
)
1094 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1097 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1100 memset(&ifr
, 0, sizeof(ifr
));
1101 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1102 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1104 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1108 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1109 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1111 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1116 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1119 static sessiont
*sessiontbysessionidt(sessionidt s
)
1121 if (!s
|| s
>= MAXSESSION
) return NULL
;
1125 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1127 sessionidt val
= s
-session
;
1128 if (s
< session
|| val
>= MAXSESSION
) return 0;
1132 // actually send a control message for a specific tunnel
1133 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1135 struct sockaddr_in addr
;
1141 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1142 STAT(tunnel_tx_errors
);
1148 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1149 STAT(tunnel_tx_errors
);
1153 memset(&addr
, 0, sizeof(addr
));
1154 addr
.sin_family
= AF_INET
;
1155 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1156 addr
.sin_port
= htons(tunnel
[t
].port
);
1158 // sequence expected, if sequence in message
1159 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1161 // If this is a control message, deal with retries
1164 tunnel
[t
].last
= time_now
; // control message sent
1165 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1168 STAT(tunnel_retries
);
1169 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1173 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1175 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1176 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1177 STAT(tunnel_tx_errors
);
1181 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1182 STAT(tunnel_tx_packets
);
1183 INC_STAT(tunnel_tx_bytes
, l
);
1187 // Tiny helper function to write data to
1188 // the 'tun' device.
1190 int tun_write(uint8_t * data
, int size
)
1192 return write(tunfd
, data
, size
);
1195 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1196 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1198 int d
= (tcp
[12] >> 4) * 4;
1205 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1208 if (tcp
+ d
> buf
+ len
) // short?
1216 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1219 if (mss
+ 2 > data
) return; // short?
1223 if (*opts
== 0) return; // end of options
1224 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1227 opts
+= opts
[1]; // skip over option
1230 if (!mss
) return; // not found
1231 orig
= ntohs(*(uint16_t *) mss
);
1233 if (orig
<= MSS
) return; // mss OK
1235 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1236 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1237 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1238 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1241 *(int16_t *) mss
= htons(MSS
);
1243 // adjust checksum (see rfc1141)
1244 sum
= orig
+ (~MSS
& 0xffff);
1245 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1246 sum
= (sum
& 0xffff) + (sum
>> 16);
1247 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1250 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1254 // Skip the four extra bytes
1266 proto
= ntohs(*(uint16_t *) p
);
1274 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1275 return; // closing session, PPP not processed
1277 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1278 processipin(s
, t
, p
, l
);
1280 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1284 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1285 return; // closing session, PPP not processed
1288 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1289 processipv6in(s
, t
, p
, l
);
1291 else if (proto
== PPPIPCP
)
1293 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1294 processipcp(s
, t
, p
, l
);
1296 else if (proto
== PPPCCP
)
1298 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1299 processccp(s
, t
, p
, l
);
1303 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1307 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1309 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1310 sp
->cout_delta
+= len
;
1312 sp
->last_data
= time_now
;
1314 sess_local
[s
].cout
+= len
; // To send to master..
1315 sess_local
[s
].pout
++;
1318 // process outgoing (to tunnel) IP
1320 static void processipout(uint8_t *buf
, int len
)
1327 uint8_t *data
= buf
; // Keep a copy of the originals.
1330 uint8_t fragbuf
[MAXETHER
+ 20];
1332 CSTAT(processipout
);
1334 if (len
< MIN_IP_SIZE
)
1336 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1337 STAT(tun_rx_errors
);
1340 if (len
>= MAXETHER
)
1342 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1343 STAT(tun_rx_errors
);
1347 // Skip the tun header
1351 // Got an IP header now
1352 if (*(uint8_t *)(buf
) >> 4 != 4)
1354 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1358 ip
= *(uint32_t *)(buf
+ 16);
1359 if (!(s
= sessionbyip(ip
)))
1361 // Is this a packet for a session that doesn't exist?
1362 static int rate
= 0; // Number of ICMP packets we've sent this second.
1363 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1365 if (last
!= time_now
)
1371 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1373 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1374 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1375 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1380 t
= session
[s
].tunnel
;
1381 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1383 LOG(3, s
, t
, "Packet size more than session MRU\n");
1389 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1390 if (config
->max_packets
> 0)
1392 if (sess_local
[s
].last_packet_out
== TIME
)
1394 int max
= config
->max_packets
;
1396 // All packets for throttled sessions are handled by the
1397 // master, so further limit by using the throttle rate.
1398 // A bit of a kludge, since throttle rate is in kbps,
1399 // but should still be generous given our average DSL
1400 // packet size is 200 bytes: a limit of 28kbps equates
1401 // to around 180 packets per second.
1402 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1403 max
= sp
->throttle_out
;
1405 if (++sess_local
[s
].packets_out
> max
)
1407 sess_local
[s
].packets_dropped
++;
1413 if (sess_local
[s
].packets_dropped
)
1415 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1416 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1417 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1418 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1422 sess_local
[s
].last_packet_out
= TIME
;
1423 sess_local
[s
].packets_out
= 1;
1424 sess_local
[s
].packets_dropped
= 0;
1428 // run access-list if any
1429 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1432 // adjust MSS on SYN and SYN,ACK packets with options
1433 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1435 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1436 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1437 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1442 // Are we throttling this session?
1443 if (config
->cluster_iam_master
)
1444 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1446 master_throttle_packet(sp
->tbf_out
, data
, size
);
1450 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1452 // We are walled-gardening this
1453 master_garden_packet(s
, data
, size
);
1457 // Add on L2TP header
1460 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1462 bid
= session
[s
].bundle
;
1463 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1464 t
= session
[s
].tunnel
;
1466 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1467 if(len
> MINFRAGLEN
)
1469 // Partition the packet to "bundle[b].num_of_links" fragments
1470 bundlet
*b
= &bundle
[bid
];
1471 uint32_t num_of_links
= b
->num_of_links
;
1472 uint32_t fraglen
= len
/ num_of_links
;
1473 fraglen
= (fraglen
> session
[s
].mru
? session
[s
].mru
: fraglen
);
1474 uint32_t last_fraglen
= fraglen
+ len
% num_of_links
;
1475 last_fraglen
= (last_fraglen
> session
[s
].mru
? len
% num_of_links
: last_fraglen
);
1476 uint32_t remain
= len
;
1478 // send the first packet
1479 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1481 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1483 update_session_out_stat(s
, sp
, fraglen
);
1485 while (remain
> last_fraglen
)
1487 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1488 t
= session
[s
].tunnel
;
1490 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1491 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1493 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1494 update_session_out_stat(s
, sp
, fraglen
);
1497 // send the last fragment
1498 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1499 t
= session
[s
].tunnel
;
1501 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1502 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1504 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1505 update_session_out_stat(s
, sp
, remain
);
1506 if (remain
!= last_fraglen
)
1507 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1510 // Send it as one frame
1511 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1513 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1514 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1515 update_session_out_stat(s
, sp
, len
);
1520 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1522 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1523 update_session_out_stat(s
, sp
, len
);
1527 // Snooping this session, send it to intercept box
1528 if (sp
->snoop_ip
&& sp
->snoop_port
)
1529 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1534 // process outgoing (to tunnel) IPv6
1536 static void processipv6out(uint8_t * buf
, int len
)
1542 struct in6_addr ip6
;
1544 uint8_t *data
= buf
; // Keep a copy of the originals.
1547 uint8_t b
[MAXETHER
+ 20];
1549 CSTAT(processipv6out
);
1551 if (len
< MIN_IP_SIZE
)
1553 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1554 STAT(tunnel_tx_errors
);
1557 if (len
>= MAXETHER
)
1559 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1560 STAT(tunnel_tx_errors
);
1564 // Skip the tun header
1568 // Got an IP header now
1569 if (*(uint8_t *)(buf
) >> 4 != 6)
1571 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1575 ip6
= *(struct in6_addr
*)(buf
+24);
1576 s
= sessionbyipv6(ip6
);
1580 ip
= *(uint32_t *)(buf
+ 32);
1581 s
= sessionbyip(ip
);
1586 // Is this a packet for a session that doesn't exist?
1587 static int rate
= 0; // Number of ICMP packets we've sent this second.
1588 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1590 if (last
!= time_now
)
1596 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1598 // FIXME: Should send icmp6 host unreachable
1602 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1604 bundleidt bid
= session
[s
].bundle
;
1605 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1606 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1608 t
= session
[s
].tunnel
;
1610 sp
->last_data
= time_now
;
1612 // FIXME: add DoS prevention/filters?
1616 // Are we throttling this session?
1617 if (config
->cluster_iam_master
)
1618 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1620 master_throttle_packet(sp
->tbf_out
, data
, size
);
1623 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1625 // We are walled-gardening this
1626 master_garden_packet(s
, data
, size
);
1630 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1632 // Add on L2TP header
1634 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1636 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1639 // Snooping this session, send it to intercept box
1640 if (sp
->snoop_ip
&& sp
->snoop_port
)
1641 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1643 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1644 sp
->cout_delta
+= len
;
1648 sess_local
[s
].cout
+= len
; // To send to master..
1649 sess_local
[s
].pout
++;
1653 // Helper routine for the TBF filters.
1654 // Used to send queued data in to the user!
1656 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1662 uint8_t b
[MAXETHER
+ 20];
1664 if (len
< 0 || len
> MAXETHER
)
1666 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1670 // Skip the tun header
1674 ip
= *(in_addr_t
*)(buf
+ 16);
1679 t
= session
[s
].tunnel
;
1682 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1684 // Add on L2TP header
1686 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1688 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1691 // Snooping this session.
1692 if (sp
->snoop_ip
&& sp
->snoop_port
)
1693 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1695 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1696 sp
->cout_delta
+= len
;
1700 sess_local
[s
].cout
+= len
; // To send to master..
1701 sess_local
[s
].pout
++;
1704 // add an AVP (16 bit)
1705 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1707 uint16_t l
= (m
? 0x8008 : 0x0008);
1708 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1709 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1710 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1711 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1715 // add an AVP (32 bit)
1716 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1718 uint16_t l
= (m
? 0x800A : 0x000A);
1719 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1720 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1721 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1722 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1726 // add an AVP (string)
1727 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1729 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1730 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1731 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1732 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1733 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1734 c
->length
+= 6 + strlen(val
);
1738 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1740 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1741 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1742 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1743 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1744 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1745 c
->length
+= 6 + len
;
1748 // new control connection
1749 static controlt
*controlnew(uint16_t mtype
)
1753 c
= malloc(sizeof(controlt
));
1757 controlfree
= c
->next
;
1761 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1763 control16(c
, 0, mtype
, 1);
1767 // send zero block if nothing is waiting
1769 static void controlnull(tunnelidt t
)
1772 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1775 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1776 *(uint16_t *) (buf
+ 2) = htons(12); // length
1777 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1778 *(uint16_t *) (buf
+ 6) = htons(0); // session
1779 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1780 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1781 tunnelsend(buf
, 12, t
);
1784 // add a control message to a tunnel, and send if within window
1785 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1787 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1788 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1789 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1790 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1791 tunnel
[t
].ns
++; // advance sequence
1792 // link in message in to queue
1793 if (tunnel
[t
].controlc
)
1794 tunnel
[t
].controle
->next
= c
;
1796 tunnel
[t
].controls
= c
;
1798 tunnel
[t
].controle
= c
;
1799 tunnel
[t
].controlc
++;
1801 // send now if space in window
1802 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1804 tunnel
[t
].try = 0; // first send
1805 tunnelsend(c
->buf
, c
->length
, t
);
1810 // Throttle or Unthrottle a session
1812 // Throttle the data from/to through a session to no more than
1813 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1816 // If either value is -1, the current value is retained for that
1819 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1821 if (!session
[s
].opened
)
1822 return; // No-one home.
1824 if (!*session
[s
].user
)
1825 return; // User not logged in
1829 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1830 if (session
[s
].tbf_in
)
1831 free_tbf(session
[s
].tbf_in
);
1834 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1836 session
[s
].tbf_in
= 0;
1838 session
[s
].throttle_in
= rate_in
;
1843 int bytes
= rate_out
* 1024 / 8;
1844 if (session
[s
].tbf_out
)
1845 free_tbf(session
[s
].tbf_out
);
1848 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1850 session
[s
].tbf_out
= 0;
1852 session
[s
].throttle_out
= rate_out
;
1856 // add/remove filters from session (-1 = no change)
1857 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1859 if (!session
[s
].opened
)
1860 return; // No-one home.
1862 if (!*session
[s
].user
)
1863 return; // User not logged in
1866 if (filter_in
> MAXFILTER
) filter_in
= -1;
1867 if (filter_out
> MAXFILTER
) filter_out
= -1;
1868 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1869 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1873 if (session
[s
].filter_in
)
1874 ip_filters
[session
[s
].filter_in
- 1].used
--;
1877 ip_filters
[filter_in
- 1].used
++;
1879 session
[s
].filter_in
= filter_in
;
1882 if (filter_out
>= 0)
1884 if (session
[s
].filter_out
)
1885 ip_filters
[session
[s
].filter_out
- 1].used
--;
1888 ip_filters
[filter_out
- 1].used
++;
1890 session
[s
].filter_out
= filter_out
;
1894 // start tidy shutdown of session
1895 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1897 int walled_garden
= session
[s
].walled_garden
;
1898 bundleidt b
= session
[s
].bundle
;
1899 //delete routes only for last session in bundle (in case of MPPP)
1900 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1902 CSTAT(sessionshutdown
);
1904 if (!session
[s
].opened
)
1906 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1907 return; // not a live session
1910 if (!session
[s
].die
)
1912 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1913 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1914 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1915 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1918 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1920 // RADIUS Stop message
1921 uint16_t r
= radiusnew(s
);
1924 // stop, if not already trying
1925 if (radius
[r
].state
!= RADIUSSTOP
)
1927 radius
[r
].term_cause
= term_cause
;
1928 radius
[r
].term_msg
= reason
;
1929 radiussend(r
, RADIUSSTOP
);
1933 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1935 // Save counters to dump to accounting file
1936 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1937 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1941 { // IP allocated, clear and unroute
1944 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1946 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
1947 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
1950 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
1951 session
[s
].route
[r
].ip
= 0;
1954 if (session
[s
].ip_pool_index
== -1) // static ip
1956 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1962 // unroute IPv6, if setup
1963 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
1964 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1968 // This session was part of a bundle
1969 bundle
[b
].num_of_links
--;
1970 LOG(3, s
, 0, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
1971 if(bundle
[b
].num_of_links
== 0)
1974 LOG(3, s
, 0, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
1978 // Adjust the members array to accomodate the new change
1979 uint8_t mem_num
= 0;
1980 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
1981 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
1984 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
1985 if(bundle
[b
].members
[ml
] == s
)
1990 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
1991 LOG(3, s
, 0, "MPPP: Adjusted member links array\n");
1994 cluster_send_bundle(b
);
1998 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1999 throttle_session(s
, 0, 0);
2003 controlt
*c
= controlnew(14); // sending CDN
2007 *(uint16_t *) buf
= htons(cdn_result
);
2008 *(uint16_t *) (buf
+2) = htons(cdn_error
);
2009 controlb(c
, 1, buf
, 4, 1);
2012 control16(c
, 1, cdn_result
, 1);
2014 control16(c
, 14, s
, 1); // assigned session (our end)
2015 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2018 // update filter refcounts
2019 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2020 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2023 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2024 sess_local
[s
].lcp
.restart
= 0;
2025 sess_local
[s
].ipcp
.restart
= 0;
2026 sess_local
[s
].ipv6cp
.restart
= 0;
2027 sess_local
[s
].ccp
.restart
= 0;
2029 cluster_send_session(s
);
2032 void sendipcp(sessionidt s
, tunnelidt t
)
2034 uint8_t buf
[MAXETHER
];
2038 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2040 if (!session
[s
].unique_id
)
2042 if (!++last_id
) ++last_id
; // skip zero
2043 session
[s
].unique_id
= last_id
;
2046 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2050 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2051 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2052 q
[4] = 3; // ip address option
2053 q
[5] = 6; // option length
2054 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2055 config
->bind_address
? config
->bind_address
:
2056 my_address
; // send my IP
2058 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2059 restart_timer(s
, ipcp
);
2062 void sendipv6cp(sessionidt s
, tunnelidt t
)
2064 uint8_t buf
[MAXETHER
];
2068 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2070 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2074 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2075 // only send one type
2077 *(uint16_t *) (q
+ 2) = htons(14);
2078 q
[4] = 1; // interface identifier option
2079 q
[5] = 10; // option length
2080 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2081 *(uint32_t *) (q
+ 10) = 0;
2084 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2085 restart_timer(s
, ipv6cp
);
2088 static void sessionclear(sessionidt s
)
2090 memset(&session
[s
], 0, sizeof(session
[s
]));
2091 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2092 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2094 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2095 session
[s
].next
= sessionfree
;
2099 // kill a session now
2100 void sessionkill(sessionidt s
, char *reason
)
2104 if (!session
[s
].opened
) // not alive
2107 if (session
[s
].next
)
2109 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2113 if (!session
[s
].die
)
2114 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2116 if (sess_local
[s
].radius
)
2117 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2119 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2121 cluster_send_session(s
);
2124 static void tunnelclear(tunnelidt t
)
2127 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2128 tunnel
[t
].state
= TUNNELFREE
;
2131 static void bundleclear(bundleidt b
)
2134 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2135 bundle
[b
].state
= BUNDLEFREE
;
2138 // kill a tunnel now
2139 static void tunnelkill(tunnelidt t
, char *reason
)
2146 tunnel
[t
].state
= TUNNELDIE
;
2148 // free control messages
2149 while ((c
= tunnel
[t
].controls
))
2151 controlt
* n
= c
->next
;
2152 tunnel
[t
].controls
= n
;
2153 tunnel
[t
].controlc
--;
2154 c
->next
= controlfree
;
2158 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2159 if (session
[s
].tunnel
== t
)
2160 sessionkill(s
, reason
);
2164 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2165 cli_tunnel_actions
[t
].action
= 0;
2166 cluster_send_tunnel(t
);
2169 // shut down a tunnel cleanly
2170 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2174 CSTAT(tunnelshutdown
);
2176 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2178 // never set up, can immediately kill
2179 tunnelkill(t
, reason
);
2182 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2185 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2186 if (session
[s
].tunnel
== t
)
2187 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2189 tunnel
[t
].state
= TUNNELDIE
;
2190 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2191 cluster_send_tunnel(t
);
2192 // TBA - should we wait for sessions to stop?
2195 controlt
*c
= controlnew(4); // sending StopCCN
2200 *(uint16_t *) buf
= htons(result
);
2201 *(uint16_t *) (buf
+2) = htons(error
);
2204 int m
= strlen(msg
);
2205 if (m
+ 4 > sizeof(buf
))
2206 m
= sizeof(buf
) - 4;
2208 memcpy(buf
+4, msg
, m
);
2212 controlb(c
, 1, buf
, l
, 1);
2215 control16(c
, 1, result
, 1);
2217 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2218 controladd(c
, 0, t
); // send the message
2222 // read and process packet on tunnel (UDP)
2223 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2225 uint8_t *chapresponse
= NULL
;
2226 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2227 uint8_t *p
= buf
+ 2;
2234 LOG_HEX(5, "UDP Data", buf
, len
);
2235 STAT(tunnel_rx_packets
);
2236 INC_STAT(tunnel_rx_bytes
, len
);
2239 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2240 STAT(tunnel_rx_errors
);
2243 if ((buf
[1] & 0x0F) != 2)
2245 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2246 STAT(tunnel_rx_errors
);
2251 l
= ntohs(*(uint16_t *) p
);
2254 t
= ntohs(*(uint16_t *) p
);
2256 s
= ntohs(*(uint16_t *) p
);
2258 if (s
>= MAXSESSION
)
2260 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2261 STAT(tunnel_rx_errors
);
2266 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2267 STAT(tunnel_rx_errors
);
2272 ns
= ntohs(*(uint16_t *) p
);
2274 nr
= ntohs(*(uint16_t *) p
);
2279 uint16_t o
= ntohs(*(uint16_t *) p
);
2284 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2285 STAT(tunnel_rx_errors
);
2290 // used to time out old tunnels
2291 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2292 tunnel
[t
].lastrec
= time_now
;
2296 uint16_t message
= 0xFFFF; // message type
2298 uint8_t mandatory
= 0;
2299 uint16_t asession
= 0; // assigned session
2300 uint32_t amagic
= 0; // magic number
2301 uint8_t aflags
= 0; // flags from last LCF
2302 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2303 char called
[MAXTEL
] = ""; // called number
2304 char calling
[MAXTEL
] = ""; // calling number
2306 if (!config
->cluster_iam_master
)
2308 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2312 // control messages must have bits 0x80|0x40|0x08
2313 // (type, length and sequence) set, and bits 0x02|0x01
2314 // (offset and priority) clear
2315 if ((*buf
& 0xCB) != 0xC8)
2317 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2318 STAT(tunnel_rx_errors
);
2322 // check for duplicate tunnel open message
2328 // Is this a duplicate of the first packet? (SCCRQ)
2330 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2332 if (tunnel
[i
].state
!= TUNNELOPENING
||
2333 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2334 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2337 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2342 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2343 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2345 // if no tunnel specified, assign one
2348 if (!(t
= new_tunnel()))
2350 LOG(1, 0, 0, "No more tunnels\n");
2351 STAT(tunnel_overflow
);
2355 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2356 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2357 tunnel
[t
].window
= 4; // default window
2358 STAT(tunnel_created
);
2359 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2360 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2363 // If the 'ns' just received is not the 'nr' we're
2364 // expecting, just send an ack and drop it.
2366 // if 'ns' is less, then we got a retransmitted packet.
2367 // if 'ns' is greater than missed a packet. Either way
2368 // we should ignore it.
2369 if (ns
!= tunnel
[t
].nr
)
2371 // is this the sequence we were expecting?
2372 STAT(tunnel_rx_errors
);
2373 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2374 t
, ns
, tunnel
[t
].nr
);
2376 if (l
) // Is this not a ZLB?
2381 // check sequence of this message
2383 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2384 // some to clear maybe?
2385 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2387 controlt
*c
= tunnel
[t
].controls
;
2388 tunnel
[t
].controls
= c
->next
;
2389 tunnel
[t
].controlc
--;
2390 c
->next
= controlfree
;
2393 tunnel
[t
].try = 0; // we have progress
2396 // receiver advance (do here so quoted correctly in any sends below)
2397 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2398 if (skip
< 0) skip
= 0;
2399 if (skip
< tunnel
[t
].controlc
)
2401 // some control packets can now be sent that were previous stuck out of window
2402 int tosend
= tunnel
[t
].window
- skip
;
2403 controlt
*c
= tunnel
[t
].controls
;
2411 tunnel
[t
].try = 0; // first send
2412 tunnelsend(c
->buf
, c
->length
, t
);
2417 if (!tunnel
[t
].controlc
)
2418 tunnel
[t
].retry
= 0; // caught up
2421 { // if not a null message
2426 // Default disconnect cause/message on receipt of CDN. Set to
2427 // more specific value from attribute 1 (result code) or 46
2428 // (disconnect cause) if present below.
2429 int disc_cause_set
= 0;
2430 int disc_cause
= TERM_NAS_REQUEST
;
2431 char const *disc_reason
= "Closed (Received CDN).";
2434 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2436 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2443 LOG(1, s
, t
, "Invalid length in AVP\n");
2444 STAT(tunnel_rx_errors
);
2449 if (flags
& 0x3C) // reserved bits, should be clear
2451 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2453 result
= 2; // general error
2454 error
= 3; // reserved field non-zero
2459 if (*(uint16_t *) (b
))
2461 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2463 result
= 2; // general error
2464 error
= 6; // generic vendor-specific error
2465 msg
= "unsupported vendor-specific";
2469 mtype
= ntohs(*(uint16_t *) (b
));
2477 // handle hidden AVPs
2478 if (!*config
->l2tp_secret
)
2480 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2482 result
= 2; // general error
2483 error
= 6; // generic vendor-specific error
2484 msg
= "secret not specified";
2487 if (!session
[s
].random_vector_length
)
2489 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2491 result
= 2; // general error
2492 error
= 6; // generic
2493 msg
= "no random vector";
2498 LOG(2, s
, t
, "Short hidden AVP.\n");
2500 result
= 2; // general error
2501 error
= 2; // length is wrong
2507 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2509 orig_len
= ntohs(*(uint16_t *) b
);
2510 if (orig_len
> n
+ 2)
2512 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2516 result
= 2; // general error
2517 error
= 2; // length is wrong
2526 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2527 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2531 case 0: // message type
2532 message
= ntohs(*(uint16_t *) b
);
2533 mandatory
= flags
& 0x80;
2534 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2536 case 1: // result code
2538 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2539 char const *resdesc
= "(unknown)";
2540 char const *errdesc
= NULL
;
2545 resdesc
= l2tp_stopccn_result_code(rescode
);
2546 cause
= TERM_LOST_SERVICE
;
2548 else if (message
== 14)
2550 resdesc
= l2tp_cdn_result_code(rescode
);
2552 cause
= TERM_LOST_CARRIER
;
2554 cause
= TERM_ADMIN_RESET
;
2557 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2560 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2561 errdesc
= l2tp_error_code(errcode
);
2562 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2565 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2567 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2569 disc_cause_set
= mtype
;
2570 disc_reason
= errdesc
? errdesc
: resdesc
;
2577 case 2: // protocol version
2579 version
= ntohs(*(uint16_t *) (b
));
2580 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2581 if (version
&& version
!= 0x0100)
2582 { // allow 0.0 and 1.0
2583 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2585 result
= 5; // unspported protocol version
2586 error
= 0x0100; // supported version
2592 case 3: // framing capabilities
2594 case 4: // bearer capabilities
2596 case 5: // tie breaker
2597 // We never open tunnels, so we don't care about tie breakers
2599 case 6: // firmware revision
2601 case 7: // host name
2602 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2603 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2604 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2605 // TBA - to send to RADIUS
2607 case 8: // vendor name
2608 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2609 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2610 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2612 case 9: // assigned tunnel
2613 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2614 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2616 case 10: // rx window
2617 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2618 if (!tunnel
[t
].window
)
2619 tunnel
[t
].window
= 1; // window of 0 is silly
2620 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2622 case 11: // Challenge
2624 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2625 build_chap_response(b
, 2, n
, &chapresponse
);
2628 case 13: // Response
2629 // Why did they send a response? We never challenge.
2630 LOG(2, s
, t
, " received unexpected challenge response\n");
2633 case 14: // assigned session
2634 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2635 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2637 case 15: // call serial number
2638 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2640 case 18: // bearer type
2641 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2644 case 19: // framing type
2645 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2648 case 21: // called number
2649 memset(called
, 0, sizeof(called
));
2650 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2651 LOG(4, s
, t
, " Called <%s>\n", called
);
2653 case 22: // calling number
2654 memset(calling
, 0, sizeof(calling
));
2655 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2656 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2660 case 24: // tx connect speed
2663 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2667 // AS5300s send connect speed as a string
2669 memset(tmp
, 0, sizeof(tmp
));
2670 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2671 session
[s
].tx_connect_speed
= atol(tmp
);
2673 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2675 case 38: // rx connect speed
2678 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2682 // AS5300s send connect speed as a string
2684 memset(tmp
, 0, sizeof(tmp
));
2685 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2686 session
[s
].rx_connect_speed
= atol(tmp
);
2688 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2690 case 25: // Physical Channel ID
2692 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2693 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2696 case 29: // Proxy Authentication Type
2698 uint16_t atype
= ntohs(*(uint16_t *)b
);
2699 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2702 case 30: // Proxy Authentication Name
2705 memset(authname
, 0, sizeof(authname
));
2706 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2707 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2711 case 31: // Proxy Authentication Challenge
2713 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2716 case 32: // Proxy Authentication ID
2718 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2719 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2722 case 33: // Proxy Authentication Response
2723 LOG(4, s
, t
, " Proxy Auth Response\n");
2725 case 27: // last sent lcp
2726 { // find magic number
2727 uint8_t *p
= b
, *e
= p
+ n
;
2728 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2730 if (*p
== 5 && p
[1] == 6) // Magic-Number
2731 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2732 else if (*p
== 7) // Protocol-Field-Compression
2733 aflags
|= SESSION_PFC
;
2734 else if (*p
== 8) // Address-and-Control-Field-Compression
2735 aflags
|= SESSION_ACFC
;
2740 case 28: // last recv lcp confreq
2742 case 26: // Initial Received LCP CONFREQ
2744 case 39: // seq required - we control it as an LNS anyway...
2746 case 36: // Random Vector
2747 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2748 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2749 if (n
> sizeof(session
[s
].random_vector
))
2750 n
= sizeof(session
[s
].random_vector
);
2751 memcpy(session
[s
].random_vector
, b
, n
);
2752 session
[s
].random_vector_length
= n
;
2754 case 46: // ppp disconnect cause
2757 uint16_t code
= ntohs(*(uint16_t *) b
);
2758 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2759 uint8_t dir
= *(b
+ 4);
2761 LOG(4, s
, t
, " PPP disconnect cause "
2762 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2763 code
, proto
, dir
, n
- 5, b
+ 5);
2765 disc_cause_set
= mtype
;
2769 case 1: // admin disconnect
2770 disc_cause
= TERM_ADMIN_RESET
;
2771 disc_reason
= "Administrative disconnect";
2773 case 3: // lcp terminate
2774 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2775 disc_cause
= TERM_USER_REQUEST
;
2776 disc_reason
= "Normal disconnection";
2778 case 4: // compulsory encryption unavailable
2779 if (dir
!= 1) break; // 1=refused by peer, 2=local
2780 disc_cause
= TERM_USER_ERROR
;
2781 disc_reason
= "Compulsory encryption refused";
2783 case 5: // lcp: fsm timeout
2784 disc_cause
= TERM_PORT_ERROR
;
2785 disc_reason
= "LCP: FSM timeout";
2787 case 6: // lcp: no recognisable lcp packets received
2788 disc_cause
= TERM_PORT_ERROR
;
2789 disc_reason
= "LCP: no recognisable LCP packets";
2791 case 7: // lcp: magic-no error (possibly looped back)
2792 disc_cause
= TERM_PORT_ERROR
;
2793 disc_reason
= "LCP: magic-no error (possible loop)";
2795 case 8: // lcp: echo request timeout
2796 disc_cause
= TERM_PORT_ERROR
;
2797 disc_reason
= "LCP: echo request timeout";
2799 case 13: // auth: fsm timeout
2800 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2801 disc_reason
= "Authentication: FSM timeout";
2803 case 15: // auth: unacceptable auth protocol
2804 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2805 disc_reason
= "Unacceptable authentication protocol";
2807 case 16: // auth: authentication failed
2808 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2809 disc_reason
= "Authentication failed";
2811 case 17: // ncp: fsm timeout
2812 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2813 disc_reason
= "NCP: FSM timeout";
2815 case 18: // ncp: no ncps available
2816 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2817 disc_reason
= "NCP: no NCPs available";
2819 case 19: // ncp: failure to converge on acceptable address
2820 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2821 disc_reason
= (dir
== 1)
2822 ? "NCP: too many Configure-Naks received from peer"
2823 : "NCP: too many Configure-Naks sent to peer";
2825 case 20: // ncp: user not permitted to use any address
2826 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2827 disc_reason
= (dir
== 1)
2828 ? "NCP: local link address not acceptable to peer"
2829 : "NCP: remote link address not acceptable";
2836 static char e
[] = "unknown AVP 0xXXXX";
2837 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2839 result
= 2; // general error
2840 error
= 8; // unknown mandatory AVP
2841 sprintf((msg
= e
) + 14, "%04x", mtype
);
2848 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2852 case 1: // SCCRQ - Start Control Connection Request
2853 tunnel
[t
].state
= TUNNELOPENING
;
2854 if (main_quit
!= QUIT_SHUTDOWN
)
2856 controlt
*c
= controlnew(2); // sending SCCRP
2857 control16(c
, 2, version
, 1); // protocol version
2858 control32(c
, 3, 3, 1); // framing
2859 controls(c
, 7, hostname
, 1); // host name
2860 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2861 control16(c
, 9, t
, 1); // assigned tunnel
2862 controladd(c
, 0, t
); // send the resply
2866 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2870 tunnel
[t
].state
= TUNNELOPEN
;
2871 tunnel
[t
].lastrec
= time_now
;
2874 tunnel
[t
].state
= TUNNELOPEN
;
2875 tunnel
[t
].lastrec
= time_now
;
2876 controlnull(t
); // ack
2879 controlnull(t
); // ack
2880 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2883 controlnull(t
); // simply ACK
2895 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2897 controlt
*c
= controlnew(11); // ICRP
2900 sessionfree
= session
[s
].next
;
2901 memset(&session
[s
], 0, sizeof(session
[s
]));
2903 if (s
> config
->cluster_highest_sessionid
)
2904 config
->cluster_highest_sessionid
= s
;
2906 session
[s
].opened
= time_now
;
2907 session
[s
].tunnel
= t
;
2908 session
[s
].far
= asession
;
2909 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2910 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2911 control16(c
, 14, s
, 1); // assigned session
2912 controladd(c
, asession
, t
); // send the reply
2914 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2915 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2917 session
[s
].ppp
.phase
= Establish
;
2918 session
[s
].ppp
.lcp
= Starting
;
2920 STAT(session_created
);
2925 controlt
*c
= controlnew(14); // CDN
2928 STAT(session_overflow
);
2929 LOG(1, 0, t
, "No free sessions\n");
2930 control16(c
, 1, 4, 0); // temporary lack of resources
2933 control16(c
, 1, 2, 7); // shutting down, try another
2935 controladd(c
, asession
, t
); // send the message
2942 if (amagic
== 0) amagic
= time_now
;
2943 session
[s
].magic
= amagic
; // set magic number
2944 session
[s
].flags
= aflags
; // set flags received
2945 session
[s
].mru
= PPPoE_MRU
; // default
2946 controlnull(t
); // ack
2949 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
2950 sess_local
[s
].ppp_mru
= MRU
;
2952 // Set multilink options before sending initial LCP packet
2953 sess_local
[s
].mp_mrru
= 1614;
2954 sess_local
[s
].mp_epdis
= config
->bind_address
? config
->bind_address
: my_address
;
2957 change_state(s
, lcp
, RequestSent
);
2961 controlnull(t
); // ack
2962 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
2965 LOG(1, s
, t
, "Missing message type\n");
2968 STAT(tunnel_rx_errors
);
2970 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2972 LOG(1, s
, t
, "Unknown message type %u\n", message
);
2975 if (chapresponse
) free(chapresponse
);
2976 cluster_send_tunnel(t
);
2980 LOG(4, s
, t
, " Got a ZLB ack\n");
2987 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
2988 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
2989 { // HDLC address header, discard
2995 LOG(1, s
, t
, "Short ppp length %d\n", l
);
2996 STAT(tunnel_rx_errors
);
3006 proto
= ntohs(*(uint16_t *) p
);
3011 if (s
&& !session
[s
].opened
) // Is something wrong??
3013 if (!config
->cluster_iam_master
)
3015 // Pass it off to the master to deal with..
3016 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3021 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3022 STAT(tunnel_rx_errors
);
3026 if (proto
== PPPPAP
)
3028 session
[s
].last_packet
= time_now
;
3029 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3030 processpap(s
, t
, p
, l
);
3032 else if (proto
== PPPCHAP
)
3034 session
[s
].last_packet
= time_now
;
3035 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3036 processchap(s
, t
, p
, l
);
3038 else if (proto
== PPPLCP
)
3040 session
[s
].last_packet
= time_now
;
3041 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3042 processlcp(s
, t
, p
, l
);
3044 else if (proto
== PPPIPCP
)
3046 session
[s
].last_packet
= time_now
;
3047 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3048 processipcp(s
, t
, p
, l
);
3050 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3052 session
[s
].last_packet
= time_now
;
3053 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3054 processipv6cp(s
, t
, p
, l
);
3056 else if (proto
== PPPCCP
)
3058 session
[s
].last_packet
= time_now
;
3059 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3060 processccp(s
, t
, p
, l
);
3062 else if (proto
== PPPIP
)
3066 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3067 return; // closing session, PPP not processed
3070 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3071 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3073 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3077 processipin(s
, t
, p
, l
);
3079 else if (proto
== PPPMP
)
3083 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3084 return; // closing session, PPP not processed
3087 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3088 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3090 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3094 processmpin(s
, t
, p
, l
);
3096 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3100 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3101 return; // closing session, PPP not processed
3104 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3105 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3107 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3111 processipv6in(s
, t
, p
, l
);
3113 else if (session
[s
].ppp
.lcp
== Opened
)
3115 session
[s
].last_packet
= time_now
;
3116 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3117 protoreject(s
, t
, p
, l
, proto
);
3121 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3122 proto
, ppp_state(session
[s
].ppp
.lcp
));
3127 // read and process packet on tun
3128 static void processtun(uint8_t * buf
, int len
)
3130 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3131 STAT(tun_rx_packets
);
3132 INC_STAT(tun_rx_bytes
, len
);
3140 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3141 STAT(tun_rx_errors
);
3145 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3146 processipout(buf
, len
);
3147 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3148 && config
->ipv6_prefix
.s6_addr
[0])
3149 processipv6out(buf
, len
);
3154 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3155 // that we look at the whole of the tunnel, radius and session tables
3157 static void regular_cleanups(double period
)
3159 // Next tunnel, radius and session to check for actions on.
3160 static tunnelidt t
= 0;
3162 static sessionidt s
= 0;
3175 // divide up tables into slices based on the last run
3176 t_slice
= config
->cluster_highest_tunnelid
* period
;
3177 r_slice
= (MAXRADIUS
- 1) * period
;
3178 s_slice
= config
->cluster_highest_sessionid
* period
;
3182 else if (t_slice
> config
->cluster_highest_tunnelid
)
3183 t_slice
= config
->cluster_highest_tunnelid
;
3187 else if (r_slice
> (MAXRADIUS
- 1))
3188 r_slice
= MAXRADIUS
- 1;
3192 else if (s_slice
> config
->cluster_highest_sessionid
)
3193 s_slice
= config
->cluster_highest_sessionid
;
3195 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3197 for (i
= 0; i
< t_slice
; i
++)
3200 if (t
> config
->cluster_highest_tunnelid
)
3203 // check for expired tunnels
3204 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3206 STAT(tunnel_timeout
);
3207 tunnelkill(t
, "Expired");
3211 // check for message resend
3212 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3214 // resend pending messages as timeout on reply
3215 if (tunnel
[t
].retry
<= TIME
)
3217 controlt
*c
= tunnel
[t
].controls
;
3218 uint16_t w
= tunnel
[t
].window
;
3219 tunnel
[t
].try++; // another try
3220 if (tunnel
[t
].try > 5)
3221 tunnelkill(t
, "Timeout on control message"); // game over
3225 tunnelsend(c
->buf
, c
->length
, t
);
3233 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3235 controlt
*c
= controlnew(6); // sending HELLO
3236 controladd(c
, 0, t
); // send the message
3237 LOG(3, 0, t
, "Sending HELLO message\n");
3241 // Check for tunnel changes requested from the CLI
3242 if ((a
= cli_tunnel_actions
[t
].action
))
3244 cli_tunnel_actions
[t
].action
= 0;
3245 if (a
& CLI_TUN_KILL
)
3247 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3248 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3254 for (i
= 0; i
< r_slice
; i
++)
3260 if (!radius
[r
].state
)
3263 if (radius
[r
].retry
<= TIME
)
3270 for (i
= 0; i
< s_slice
; i
++)
3273 if (s
> config
->cluster_highest_sessionid
)
3276 if (!session
[s
].opened
) // Session isn't in use
3279 // check for expired sessions
3282 if (session
[s
].die
<= TIME
)
3284 sessionkill(s
, "Expired");
3291 if (sess_local
[s
].lcp
.restart
<= time_now
)
3293 int next_state
= session
[s
].ppp
.lcp
;
3294 switch (session
[s
].ppp
.lcp
)
3298 next_state
= RequestSent
;
3301 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3303 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3304 sendlcp(s
, session
[s
].tunnel
);
3305 change_state(s
, lcp
, next_state
);
3309 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3310 STAT(session_timeout
);
3320 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3322 int next_state
= session
[s
].ppp
.ipcp
;
3323 switch (session
[s
].ppp
.ipcp
)
3327 next_state
= RequestSent
;
3330 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3332 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3333 sendipcp(s
, session
[s
].tunnel
);
3334 change_state(s
, ipcp
, next_state
);
3338 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3339 STAT(session_timeout
);
3349 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3351 int next_state
= session
[s
].ppp
.ipv6cp
;
3352 switch (session
[s
].ppp
.ipv6cp
)
3356 next_state
= RequestSent
;
3359 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3361 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3362 sendipv6cp(s
, session
[s
].tunnel
);
3363 change_state(s
, ipv6cp
, next_state
);
3367 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3368 change_state(s
, ipv6cp
, Stopped
);
3375 if (sess_local
[s
].ccp
.restart
<= time_now
)
3377 int next_state
= session
[s
].ppp
.ccp
;
3378 switch (session
[s
].ppp
.ccp
)
3382 next_state
= RequestSent
;
3385 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3387 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3388 sendccp(s
, session
[s
].tunnel
);
3389 change_state(s
, ccp
, next_state
);
3393 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3394 change_state(s
, ccp
, Stopped
);
3401 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3402 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3404 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3405 STAT(session_timeout
);
3410 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3411 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3412 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3414 uint8_t b
[MAXETHER
];
3416 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3420 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3421 *(uint16_t *)(q
+ 2) = htons(8); // Length
3422 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3424 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3425 (int)(time_now
- session
[s
].last_packet
));
3426 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3427 sess_local
[s
].last_echo
= time_now
;
3431 // Drop sessions who have reached session_timeout seconds
3432 if (session
[s
].session_timeout
)
3434 bundleidt bid
= session
[s
].bundle
;
3437 if (time_now
- bundle
[bid
].last_check
>= 1)
3439 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3440 bundle
[bid
].last_check
= time_now
;
3441 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3444 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3446 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3453 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3455 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3461 // Drop sessions who have reached idle_timeout seconds
3462 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3464 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3465 STAT(session_timeout
);
3470 // Check for actions requested from the CLI
3471 if ((a
= cli_session_actions
[s
].action
))
3475 cli_session_actions
[s
].action
= 0;
3476 if (a
& CLI_SESS_KILL
)
3478 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3479 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3480 a
= 0; // dead, no need to check for other actions
3484 if (a
& CLI_SESS_NOSNOOP
)
3486 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3487 session
[s
].snoop_ip
= 0;
3488 session
[s
].snoop_port
= 0;
3492 else if (a
& CLI_SESS_SNOOP
)
3494 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3495 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3496 cli_session_actions
[s
].snoop_port
);
3498 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3499 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3504 if (a
& CLI_SESS_NOTHROTTLE
)
3506 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3507 throttle_session(s
, 0, 0);
3511 else if (a
& CLI_SESS_THROTTLE
)
3513 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3514 cli_session_actions
[s
].throttle_in
,
3515 cli_session_actions
[s
].throttle_out
);
3517 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3522 if (a
& CLI_SESS_NOFILTER
)
3524 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3525 filter_session(s
, 0, 0);
3529 else if (a
& CLI_SESS_FILTER
)
3531 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3532 cli_session_actions
[s
].filter_in
,
3533 cli_session_actions
[s
].filter_out
);
3535 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3541 cluster_send_session(s
);
3544 // RADIUS interim accounting
3545 if (config
->radius_accounting
&& config
->radius_interim
> 0
3546 && session
[s
].ip
&& !session
[s
].walled_garden
3547 && !sess_local
[s
].radius
// RADIUS already in progress
3548 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3549 && session
[s
].flags
& SESSION_STARTED
)
3551 int rad
= radiusnew(s
);
3554 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3555 STAT(radius_overflow
);
3559 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3560 session
[s
].user
, session
[s
].unique_id
);
3562 radiussend(rad
, RADIUSINTERIM
);
3563 sess_local
[s
].last_interim
= time_now
;
3568 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3569 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3573 // Are we in the middle of a tunnel update, or radius
3576 static int still_busy(void)
3579 static clockt last_talked
= 0;
3580 static clockt start_busy_wait
= 0;
3583 static time_t stopped_bgp
= 0;
3588 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3590 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3591 if (bgp_peers
[i
].state
== Established
)
3592 bgp_stop(&bgp_peers
[i
]);
3594 stopped_bgp
= time_now
;
3596 if (!config
->cluster_iam_master
)
3598 // we don't want to become master
3599 cluster_send_ping(0);
3605 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3610 if (!config
->cluster_iam_master
)
3613 if (main_quit
== QUIT_SHUTDOWN
)
3615 static int dropped
= 0;
3620 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3621 for (i
= 1; i
< MAXTUNNEL
; i
++)
3622 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3623 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3629 if (start_busy_wait
== 0)
3630 start_busy_wait
= TIME
;
3632 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3634 if (!tunnel
[i
].controlc
)
3637 if (last_talked
!= TIME
)
3639 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3645 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3646 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3648 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3652 for (i
= 1; i
< MAXRADIUS
; i
++)
3654 if (radius
[i
].state
== RADIUSNULL
)
3656 if (radius
[i
].state
== RADIUSWAIT
)
3659 if (last_talked
!= TIME
)
3661 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3671 # include <sys/epoll.h>
3673 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3674 # include "fake_epoll.h"
3677 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3680 // additional polled fds
3682 # define EXTRA_FDS BGP_NUM_PEERS
3684 # define EXTRA_FDS 0
3687 // main loop - gets packets on tun or udp and processes them
3688 static void mainloop(void)
3692 clockt next_cluster_ping
= 0; // send initial ping immediately
3693 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3694 int maxevent
= sizeof(events
)/sizeof(*events
);
3696 if ((epollfd
= epoll_create(maxevent
)) < 0)
3698 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3702 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3703 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3705 /* setup our fds to poll for input */
3707 static struct event_data d
[BASE_FDS
];
3708 struct epoll_event e
;
3715 d
[i
].type
= FD_TYPE_CLI
;
3716 e
.data
.ptr
= &d
[i
++];
3717 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3720 d
[i
].type
= FD_TYPE_CLUSTER
;
3721 e
.data
.ptr
= &d
[i
++];
3722 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3724 d
[i
].type
= FD_TYPE_TUN
;
3725 e
.data
.ptr
= &d
[i
++];
3726 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3728 d
[i
].type
= FD_TYPE_UDP
;
3729 e
.data
.ptr
= &d
[i
++];
3730 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3732 d
[i
].type
= FD_TYPE_CONTROL
;
3733 e
.data
.ptr
= &d
[i
++];
3734 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3736 d
[i
].type
= FD_TYPE_DAE
;
3737 e
.data
.ptr
= &d
[i
++];
3738 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3740 d
[i
].type
= FD_TYPE_NETLINK
;
3741 e
.data
.ptr
= &d
[i
++];
3742 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3746 signal(SIGPIPE
, SIG_IGN
);
3747 bgp_setup(config
->as_number
);
3748 if (config
->bind_address
)
3749 bgp_add_route(config
->bind_address
, 0xffffffff);
3751 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3753 if (config
->neighbour
[i
].name
[0])
3754 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3755 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3756 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
3757 0); /* 0 = routing disabled */
3761 while (!main_quit
|| still_busy())
3771 config
->reload_config
++;
3774 if (config
->reload_config
)
3776 config
->reload_config
= 0;
3784 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3785 STAT(select_called
);
3790 if (errno
== EINTR
||
3791 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3794 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3800 struct sockaddr_in addr
;
3801 struct in_addr local
;
3806 int cluster_ready
= 0;
3809 int cluster_pkts
= 0;
3811 uint32_t bgp_events
[BGP_NUM_PEERS
];
3812 memset(bgp_events
, 0, sizeof(bgp_events
));
3815 for (c
= n
, i
= 0; i
< c
; i
++)
3817 struct event_data
*d
= events
[i
].data
.ptr
;
3821 case FD_TYPE_CLI
: // CLI connections
3825 alen
= sizeof(addr
);
3826 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3832 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3838 // these are handled below, with multiple interleaved reads
3839 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3840 case FD_TYPE_TUN
: tun_ready
++; break;
3841 case FD_TYPE_UDP
: udp_ready
++; break;
3843 case FD_TYPE_CONTROL
: // nsctl commands
3844 alen
= sizeof(addr
);
3845 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3846 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3850 case FD_TYPE_DAE
: // DAE requests
3851 alen
= sizeof(addr
);
3852 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3853 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3857 case FD_TYPE_RADIUS
: // RADIUS response
3858 alen
= sizeof(addr
);
3859 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3860 if (s
>= 0 && config
->cluster_iam_master
)
3862 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3863 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3864 processrad(buf
, s
, d
->index
);
3866 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3867 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3875 bgp_events
[d
->index
] = events
[i
].events
;
3880 case FD_TYPE_NETLINK
:
3882 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
3883 s
= netlink_recv(buf
, sizeof(buf
));
3884 if (nh
->nlmsg_type
== NLMSG_ERROR
)
3886 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
3889 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
3891 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
3896 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
3901 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
);
3907 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3912 bgp_process(bgp_events
);
3915 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3920 alen
= sizeof(addr
);
3921 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3923 processudp(buf
, s
, &addr
);
3936 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3951 alen
= sizeof(addr
);
3952 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3954 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3965 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3966 STAT(multi_read_used
);
3968 if (c
>= config
->multi_read_count
)
3970 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3971 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3973 STAT(multi_read_exceeded
);
3979 /* no event received, but timers could still have expired */
3980 bgp_process_peers_timers();
3985 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
3987 // Log current traffic stats
3988 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3989 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3990 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
3991 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
3992 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
3994 udp_tx
= udp_rx
= 0;
3995 udp_rx_pkt
= eth_rx_pkt
= 0;
3996 eth_tx
= eth_rx
= 0;
3999 if (config
->dump_speed
)
4000 printf("%s\n", config
->bandwidth
);
4002 // Update the internal time counter
4003 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4007 struct param_timer p
= { time_now
};
4008 run_plugins(PLUGIN_TIMER
, &p
);
4012 // Runs on every machine (master and slaves).
4013 if (next_cluster_ping
<= TIME
)
4015 // Check to see which of the cluster is still alive..
4017 cluster_send_ping(basetime
); // Only does anything if we're a slave
4018 cluster_check_master(); // ditto.
4020 cluster_heartbeat(); // Only does anything if we're a master.
4021 cluster_check_slaves(); // ditto.
4023 master_update_counts(); // If we're a slave, send our byte counters to our master.
4025 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4026 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4028 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4031 if (!config
->cluster_iam_master
)
4034 // Run token bucket filtering queue..
4035 // Only run it every 1/10th of a second.
4037 static clockt last_run
= 0;
4038 if (last_run
!= TIME
)
4045 // Handle timeouts, retries etc.
4047 static double last_clean
= 0;
4051 TIME
= now(&this_clean
);
4052 diff
= this_clean
- last_clean
;
4054 // Run during idle time (after we've handled
4055 // all incoming packets) or every 1/10th sec
4056 if (!more
|| diff
> 0.1)
4058 regular_cleanups(diff
);
4059 last_clean
= this_clean
;
4063 if (*config
->accounting_dir
)
4065 static clockt next_acct
= 0;
4066 static clockt next_shut_acct
= 0;
4068 if (next_acct
<= TIME
)
4070 // Dump accounting data
4071 next_acct
= TIME
+ ACCT_TIME
;
4072 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4075 else if (next_shut_acct
<= TIME
)
4077 // Dump accounting data for shutdown sessions
4078 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4085 // Are we the master and shutting down??
4086 if (config
->cluster_iam_master
)
4087 cluster_heartbeat(); // Flush any queued changes..
4089 // Ok. Notify everyone we're shutting down. If we're
4090 // the master, this will force an election.
4091 cluster_send_ping(0);
4094 // Important!!! We MUST not process any packets past this point!
4095 LOG(1, 0, 0, "Shutdown complete\n");
4098 static void stripdomain(char *host
)
4102 if ((p
= strchr(host
, '.')))
4108 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4114 while (fgets(buf
, sizeof(buf
), resolv
))
4116 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4119 if (!isspace(buf
[6]))
4123 while (isspace(*b
)) b
++;
4128 while (*b
&& !isspace(*b
)) b
++;
4130 if (buf
[0] == 'd') // domain is canonical
4136 // first search line
4139 // hold, may be subsequent domain line
4140 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4151 int hl
= strlen(host
);
4152 int dl
= strlen(domain
);
4153 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4154 host
[hl
-dl
- 1] = 0;
4158 *p
= 0; // everything after first dot
4163 // Init data structures
4164 static void initdata(int optdebug
, char *optconfig
)
4168 if (!(config
= shared_malloc(sizeof(configt
))))
4170 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4174 memset(config
, 0, sizeof(configt
));
4175 time(&config
->start_time
);
4176 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4177 config
->debug
= optdebug
;
4178 config
->num_tbfs
= MAXTBFS
;
4179 config
->rl_rate
= 28; // 28kbps
4180 config
->cluster_mcast_ttl
= 1;
4181 config
->cluster_master_min_adv
= 1;
4182 config
->ppp_restart_time
= 3;
4183 config
->ppp_max_configure
= 10;
4184 config
->ppp_max_failure
= 5;
4185 config
->kill_timedout_sessions
= 1;
4186 strcpy(config
->random_device
, RANDOMDEVICE
);
4188 log_stream
= stderr
;
4191 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4193 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4196 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4199 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4201 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4204 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4206 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4209 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4211 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4214 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4216 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4219 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4221 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4225 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4227 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4231 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4233 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4237 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4239 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4243 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4245 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4248 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4250 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4252 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4255 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4257 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4259 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4262 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4264 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4265 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4266 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4267 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4268 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4270 // Put all the sessions on the free list marked as undefined.
4271 for (i
= 1; i
< MAXSESSION
; i
++)
4273 session
[i
].next
= i
+ 1;
4274 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4276 session
[MAXSESSION
- 1].next
= 0;
4279 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4280 for (i
= 1; i
< MAXTUNNEL
; i
++)
4281 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4283 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4284 bundle
[i
].state
= BUNDLEUNDEF
;
4289 if (!*config
->hostname
)
4291 // Grab my hostname unless it's been specified
4292 gethostname(hostname
, sizeof(hostname
));
4293 stripdomain(hostname
);
4296 strcpy(hostname
, config
->hostname
);
4299 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4302 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4304 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4310 static int assign_ip_address(sessionidt s
)
4314 time_t best_time
= time_now
;
4315 char *u
= session
[s
].user
;
4319 CSTAT(assign_ip_address
);
4321 for (i
= 1; i
< ip_pool_size
; i
++)
4323 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4326 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4333 if (ip_address_pool
[i
].last
< best_time
)
4336 if (!(best_time
= ip_address_pool
[i
].last
))
4337 break; // never used, grab this one
4343 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4347 session
[s
].ip
= ip_address_pool
[best
].address
;
4348 session
[s
].ip_pool_index
= best
;
4349 ip_address_pool
[best
].assigned
= 1;
4350 ip_address_pool
[best
].last
= time_now
;
4351 ip_address_pool
[best
].session
= s
;
4352 if (session
[s
].walled_garden
)
4353 /* Don't track addresses of users in walled garden (note: this
4354 means that their address isn't "sticky" even if they get
4356 ip_address_pool
[best
].user
[0] = 0;
4358 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4361 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4362 reuse
? "Reusing" : "Allocating", best
);
4367 static void free_ip_address(sessionidt s
)
4369 int i
= session
[s
].ip_pool_index
;
4372 CSTAT(free_ip_address
);
4375 return; // what the?
4377 if (i
< 0) // Is this actually part of the ip pool?
4381 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4383 ip_address_pool
[i
].assigned
= 0;
4384 ip_address_pool
[i
].session
= 0;
4385 ip_address_pool
[i
].last
= time_now
;
4389 // Fsck the address pool against the session table.
4390 // Normally only called when we become a master.
4392 // This isn't perfect: We aren't keep tracking of which
4393 // users used to have an IP address.
4395 void rebuild_address_pool(void)
4400 // Zero the IP pool allocation, and build
4401 // a map from IP address to pool index.
4402 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4404 ip_address_pool
[i
].assigned
= 0;
4405 ip_address_pool
[i
].session
= 0;
4406 if (!ip_address_pool
[i
].address
)
4409 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4412 for (i
= 0; i
< MAXSESSION
; ++i
)
4415 if (!(session
[i
].opened
&& session
[i
].ip
))
4418 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4420 if (session
[i
].ip_pool_index
< 0)
4422 // Not allocated out of the pool.
4423 if (ipid
< 1) // Not found in the pool either? good.
4426 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4427 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4429 // Fall through and process it as part of the pool.
4433 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4435 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4437 session
[i
].ip_pool_index
= ipid
;
4441 ip_address_pool
[ipid
].assigned
= 1;
4442 ip_address_pool
[ipid
].session
= i
;
4443 ip_address_pool
[ipid
].last
= time_now
;
4444 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4445 session
[i
].ip_pool_index
= ipid
;
4446 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4451 // Fix the address pool to match a changed session.
4452 // (usually when the master sends us an update).
4453 static void fix_address_pool(int sid
)
4457 ipid
= session
[sid
].ip_pool_index
;
4459 if (ipid
> ip_pool_size
)
4460 return; // Ignore it. rebuild_address_pool will fix it up.
4462 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4463 return; // Just ignore it. rebuild_address_pool will take care of it.
4465 ip_address_pool
[ipid
].assigned
= 1;
4466 ip_address_pool
[ipid
].session
= sid
;
4467 ip_address_pool
[ipid
].last
= time_now
;
4468 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4472 // Add a block of addresses to the IP pool to hand out.
4474 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4478 prefixlen
= 32; // Host route only.
4480 addr
&= 0xffffffff << (32 - prefixlen
);
4482 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4485 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4487 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4488 continue; // Skip 0 and broadcast addresses.
4490 ip_address_pool
[ip_pool_size
].address
= i
;
4491 ip_address_pool
[ip_pool_size
].assigned
= 0;
4493 if (ip_pool_size
>= MAXIPPOOL
)
4495 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4501 // Initialize the IP address pool
4502 static void initippool()
4507 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4509 if (!(f
= fopen(IPPOOLFILE
, "r")))
4511 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4515 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4518 buf
[4095] = 0; // Force it to be zero terminated/
4520 if (*buf
== '#' || *buf
== '\n')
4521 continue; // Skip comments / blank lines
4522 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4523 if ((p
= (char *)strchr(buf
, ':')))
4527 src
= inet_addr(buf
);
4528 if (src
== INADDR_NONE
)
4530 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4533 // This entry is for a specific IP only
4534 if (src
!= config
->bind_address
)
4539 if ((p
= (char *)strchr(pool
, '/')))
4543 in_addr_t start
= 0;
4545 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4547 if (!*p
|| !(numbits
= atoi(p
)))
4549 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4552 start
= ntohl(inet_addr(pool
));
4554 // Add a static route for this pool
4555 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4556 fmtaddr(htonl(start
), 0), numbits
);
4558 routeset(0, start
, numbits
, 0, 1);
4560 add_to_ip_pool(start
, numbits
);
4564 // It's a single ip address
4565 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4569 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4572 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4574 struct sockaddr_in snoop_addr
= {0};
4575 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4578 snoop_addr
.sin_family
= AF_INET
;
4579 snoop_addr
.sin_addr
.s_addr
= destination
;
4580 snoop_addr
.sin_port
= ntohs(port
);
4582 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4583 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4584 htons(snoop_addr
.sin_port
));
4586 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4587 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4589 STAT(packets_snooped
);
4592 static int dump_session(FILE **f
, sessiont
*s
)
4594 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4599 char filename
[1024];
4601 time_t now
= time(NULL
);
4603 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4604 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4606 if (!(*f
= fopen(filename
, "w")))
4608 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4612 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4613 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4618 "# format: username ip qos uptxoctets downrxoctets\n",
4620 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4625 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4626 fprintf(*f
, "%s %s %d %u %u\n",
4627 s
->user
, // username
4628 fmtaddr(htonl(s
->ip
), 0), // ip
4629 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4630 (uint32_t) s
->cin_delta
, // uptxoctets
4631 (uint32_t) s
->cout_delta
); // downrxoctets
4633 s
->cin_delta
= s
->cout_delta
= 0;
4638 static void dump_acct_info(int all
)
4644 CSTAT(dump_acct_info
);
4648 for (i
= 0; i
< shut_acct_n
; i
++)
4649 dump_session(&f
, &shut_acct
[i
]);
4655 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4656 dump_session(&f
, &session
[i
]);
4663 int main(int argc
, char *argv
[])
4667 char *optconfig
= CONFIGFILE
;
4669 time(&basetime
); // start clock
4672 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4677 if (fork()) exit(0);
4679 freopen("/dev/null", "r", stdin
);
4680 freopen("/dev/null", "w", stdout
);
4681 freopen("/dev/null", "w", stderr
);
4690 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4693 printf("Args are:\n"
4694 "\t-d\t\tDetach from terminal\n"
4695 "\t-c <file>\tConfig file\n"
4696 "\t-h <hostname>\tForce hostname\n"
4704 // Start the timer routine off
4706 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4709 initdata(optdebug
, optconfig
);
4714 init_tbf(config
->num_tbfs
);
4716 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4717 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4718 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4721 rlim
.rlim_cur
= RLIM_INFINITY
;
4722 rlim
.rlim_max
= RLIM_INFINITY
;
4723 // Remove the maximum core size
4724 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4725 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4727 // Make core dumps go to /tmp
4731 if (config
->scheduler_fifo
)
4734 struct sched_param params
= {0};
4735 params
.sched_priority
= 1;
4737 if (get_nprocs() < 2)
4739 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4740 config
->scheduler_fifo
= 0;
4744 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4746 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4750 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4751 config
->scheduler_fifo
= 0;
4758 /* Set up the cluster communications port. */
4759 if (cluster_init() < 0)
4763 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4771 unsigned seed
= time_now
^ getpid();
4772 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4776 signal(SIGHUP
, sighup_handler
);
4777 signal(SIGCHLD
, sigchild_handler
);
4778 signal(SIGTERM
, shutdown_handler
);
4779 signal(SIGINT
, shutdown_handler
);
4780 signal(SIGQUIT
, shutdown_handler
);
4782 // Prevent us from getting paged out
4783 if (config
->lock_pages
)
4785 if (!mlockall(MCL_CURRENT
))
4786 LOG(1, 0, 0, "Locking pages into memory\n");
4788 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4793 /* remove plugins (so cleanup code gets run) */
4796 // Remove the PID file if we wrote it
4797 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4798 unlink(config
->pid_file
);
4800 /* kill CLI children */
4801 signal(SIGTERM
, SIG_IGN
);
4806 static void sighup_handler(int sig
)
4811 static void shutdown_handler(int sig
)
4813 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4816 static void sigchild_handler(int sig
)
4818 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4822 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4825 *challenge_response
= NULL
;
4827 if (!*config
->l2tp_secret
)
4829 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4833 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4835 *challenge_response
= calloc(17, 1);
4838 MD5_Update(&ctx
, &id
, 1);
4839 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4840 MD5_Update(&ctx
, challenge
, challenge_length
);
4841 MD5_Final(*challenge_response
, &ctx
);
4846 static int facility_value(char *name
)
4849 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4851 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4852 return facilitynames
[i
].c_val
;
4857 static void update_config()
4861 static int timeout
= 0;
4862 static int interval
= 0;
4869 if (log_stream
!= stderr
)
4875 if (*config
->log_filename
)
4877 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4879 char *p
= config
->log_filename
+ 7;
4882 openlog("l2tpns", LOG_PID
, facility_value(p
));
4886 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4888 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4890 fseek(log_stream
, 0, SEEK_END
);
4891 setbuf(log_stream
, NULL
);
4895 log_stream
= stderr
;
4896 setbuf(log_stream
, NULL
);
4902 log_stream
= stderr
;
4903 setbuf(log_stream
, NULL
);
4906 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4907 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4909 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4910 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4911 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4913 // reset MRU/MSS globals
4914 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4915 if (MRU
> PPPoE_MRU
)
4918 MSS
= MRU
- TCP_HDRS
;
4921 config
->numradiusservers
= 0;
4922 for (i
= 0; i
< MAXRADSERVER
; i
++)
4923 if (config
->radiusserver
[i
])
4925 config
->numradiusservers
++;
4926 // Set radius port: if not set, take the port from the
4927 // first radius server. For the first radius server,
4928 // take the #defined default value from l2tpns.h
4930 // test twice, In case someone works with
4931 // a secondary radius server without defining
4932 // a primary one, this will work even then.
4933 if (i
> 0 && !config
->radiusport
[i
])
4934 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4935 if (!config
->radiusport
[i
])
4936 config
->radiusport
[i
] = RADPORT
;
4939 if (!config
->numradiusservers
)
4940 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4942 // parse radius_authtypes_s
4943 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4944 p
= config
->radius_authtypes_s
;
4947 char *s
= strpbrk(p
, " \t,");
4953 while (*s
== ' ' || *s
== '\t')
4960 if (!strncasecmp("chap", p
, strlen(p
)))
4962 else if (!strncasecmp("pap", p
, strlen(p
)))
4965 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4967 config
->radius_authtypes
|= type
;
4968 if (!config
->radius_authprefer
)
4969 config
->radius_authprefer
= type
;
4974 if (!config
->radius_authtypes
)
4976 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4977 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4980 // normalise radius_authtypes_s
4981 if (config
->radius_authprefer
== AUTHPAP
)
4983 strcpy(config
->radius_authtypes_s
, "pap");
4984 if (config
->radius_authtypes
& AUTHCHAP
)
4985 strcat(config
->radius_authtypes_s
, ", chap");
4989 strcpy(config
->radius_authtypes_s
, "chap");
4990 if (config
->radius_authtypes
& AUTHPAP
)
4991 strcat(config
->radius_authtypes_s
, ", pap");
4994 if (!config
->radius_dae_port
)
4995 config
->radius_dae_port
= DAEPORT
;
4997 // re-initialise the random number source
4998 initrandom(config
->random_device
);
5001 for (i
= 0; i
< MAXPLUGINS
; i
++)
5003 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5006 if (*config
->plugins
[i
])
5009 add_plugin(config
->plugins
[i
]);
5011 else if (*config
->old_plugins
[i
])
5014 remove_plugin(config
->old_plugins
[i
]);
5019 guest_accounts_num
= 0;
5020 char *p2
= config
->guest_user
;
5023 char *s
= strpbrk(p2
, " \t,");
5027 while (*s
== ' ' || *s
== '\t')
5034 strcpy(guest_users
[guest_accounts_num
], p2
);
5035 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5036 guest_accounts_num
++;
5039 // Rebuild the guest_user array
5040 strcpy(config
->guest_user
, "");
5042 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5044 strcat(config
->guest_user
, guest_users
[ui
]);
5045 if (ui
<guest_accounts_num
-1)
5047 strcat(config
->guest_user
, ",");
5052 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5053 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5054 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5055 if (!*config
->cluster_interface
)
5056 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5058 if (!config
->cluster_hb_interval
)
5059 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5061 if (!config
->cluster_hb_timeout
)
5062 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5064 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5066 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5067 // late, ensure we're sufficiently larger than that
5068 int t
= 4 * config
->cluster_hb_interval
+ 11;
5070 if (config
->cluster_hb_timeout
< t
)
5072 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5073 config
->cluster_hb_timeout
= t
;
5076 // Push timing changes to the slaves immediately if we're the master
5077 if (config
->cluster_iam_master
)
5078 cluster_heartbeat();
5080 interval
= config
->cluster_hb_interval
;
5081 timeout
= config
->cluster_hb_timeout
;
5085 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5088 if ((f
= fopen(config
->pid_file
, "w")))
5090 fprintf(f
, "%d\n", getpid());
5092 config
->wrote_pid
= 1;
5096 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5101 static void read_config_file()
5105 if (!config
->config_file
) return;
5106 if (!(f
= fopen(config
->config_file
, "r")))
5108 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5112 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5114 LOG(3, 0, 0, "Done reading config file\n");
5118 int sessionsetup(sessionidt s
, tunnelidt t
)
5120 // A session now exists, set it up
5126 CSTAT(sessionsetup
);
5128 LOG(3, s
, t
, "Doing session setup for session\n");
5130 // Join a bundle if the MRRU option is accepted
5131 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5133 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5134 if (join_bundle(s
) > 0)
5135 cluster_send_bundle(session
[s
].bundle
);
5138 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5139 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5146 assign_ip_address(s
);
5149 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5150 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5153 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5154 fmtaddr(htonl(session
[s
].ip
), 0));
5158 // Make sure this is right
5159 session
[s
].tunnel
= t
;
5161 // zap old sessions with same IP and/or username
5162 // Don't kill gardened sessions - doing so leads to a DoS
5163 // from someone who doesn't need to know the password
5166 user
= session
[s
].user
;
5167 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5169 if (i
== s
) continue;
5170 if (!session
[s
].opened
) continue;
5171 // Allow duplicate sessions for multilink ones of the same bundle.
5172 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5174 if (ip
== session
[i
].ip
)
5176 sessionkill(i
, "Duplicate IP address");
5180 if (config
->allow_duplicate_users
) continue;
5181 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5185 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5187 if (!strcasecmp(user
, guest_users
[gu
]))
5193 if (found
) continue;
5195 // Drop the new session in case of duplicate sessionss, not the old one.
5196 if (!strcasecmp(user
, session
[i
].user
))
5197 sessionkill(i
, "Duplicate session for users");
5201 // no need to set a route for the same IP address of the bundle
5202 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5206 // Add the route for this session.
5207 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5209 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5210 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5213 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5216 // Static IPs need to be routed if not already
5217 // convered by a Framed-Route. Anything else is part
5218 // of the IP address pool and is already routed, it
5219 // just needs to be added to the IP cache.
5220 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5221 if (session
[s
].ip_pool_index
== -1) // static ip
5223 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5226 cache_ipmap(session
[s
].ip
, s
);
5229 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5230 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5232 // Run the plugin's against this new session.
5234 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5235 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5238 // Allocate TBFs if throttled
5239 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5240 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5242 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5244 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5245 fmtaddr(htonl(session
[s
].ip
), 0),
5246 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5248 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5250 return 1; // RADIUS OK and IP allocated, done...
5254 // This session just got dropped on us by the master or something.
5255 // Make sure our tables up up to date...
5257 int load_session(sessionidt s
, sessiont
*new)
5263 if (new->ip_pool_index
>= MAXIPPOOL
||
5264 new->tunnel
>= MAXTUNNEL
)
5266 LOG(0, s
, 0, "Strange session update received!\n");
5267 // FIXME! What to do here?
5272 // Ok. All sanity checks passed. Now we're committed to
5273 // loading the new session.
5276 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5278 // See if routes/ip cache need updating
5279 if (new->ip
!= session
[s
].ip
)
5282 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5283 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5284 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5292 // remove old routes...
5293 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5295 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5296 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5299 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5305 if (session
[s
].ip_pool_index
== -1) // static IP
5307 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5309 else // It's part of the IP pool, remove it manually.
5310 uncache_ipmap(session
[s
].ip
);
5315 // add new routes...
5316 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5318 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5319 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5322 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5328 // If there's a new one, add it.
5329 if (new->ip_pool_index
== -1)
5331 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5334 cache_ipmap(new->ip
, s
);
5339 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5340 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5343 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5345 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5349 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5351 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5352 new->filter_out
= 0;
5355 if (new->filter_in
!= session
[s
].filter_in
)
5357 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5358 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5361 if (new->filter_out
!= session
[s
].filter_out
)
5363 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5364 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5367 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5368 // for walking the sessions to forward byte counts to the master.
5369 config
->cluster_highest_sessionid
= s
;
5371 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5373 // Do fixups into address pool.
5374 if (new->ip_pool_index
!= -1)
5375 fix_address_pool(s
);
5380 static void initplugins()
5384 loaded_plugins
= ll_init();
5385 // Initialize the plugins to nothing
5386 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5387 plugins
[i
] = ll_init();
5390 static void *open_plugin(char *plugin_name
, int load
)
5392 char path
[256] = "";
5394 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5395 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5396 return dlopen(path
, RTLD_NOW
);
5399 // plugin callback to get a config value
5400 static void *getconfig(char *key
, enum config_typet type
)
5404 for (i
= 0; config_values
[i
].key
; i
++)
5406 if (!strcmp(config_values
[i
].key
, key
))
5408 if (config_values
[i
].type
== type
)
5409 return ((void *) config
) + config_values
[i
].offset
;
5411 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5412 key
, type
, config_values
[i
].type
);
5418 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5422 static int add_plugin(char *plugin_name
)
5424 static struct pluginfuncs funcs
= {
5429 sessiontbysessionidt
,
5430 sessionidtbysessiont
,
5437 cluster_send_session
,
5440 void *p
= open_plugin(plugin_name
, 1);
5441 int (*initfunc
)(struct pluginfuncs
*);
5446 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5450 if (ll_contains(loaded_plugins
, p
))
5453 return 0; // already loaded
5457 int *v
= dlsym(p
, "plugin_api_version");
5458 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5460 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5466 if ((initfunc
= dlsym(p
, "plugin_init")))
5468 if (!initfunc(&funcs
))
5470 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5476 ll_push(loaded_plugins
, p
);
5478 for (i
= 0; i
< max_plugin_functions
; i
++)
5481 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5483 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5484 ll_push(plugins
[i
], x
);
5488 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5492 static void run_plugin_done(void *plugin
)
5494 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5500 static int remove_plugin(char *plugin_name
)
5502 void *p
= open_plugin(plugin_name
, 0);
5508 if (ll_contains(loaded_plugins
, p
))
5511 for (i
= 0; i
< max_plugin_functions
; i
++)
5514 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5515 ll_delete(plugins
[i
], x
);
5518 ll_delete(loaded_plugins
, p
);
5524 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5528 int run_plugins(int plugin_type
, void *data
)
5530 int (*func
)(void *data
);
5532 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5533 return PLUGIN_RET_ERROR
;
5535 ll_reset(plugins
[plugin_type
]);
5536 while ((func
= ll_next(plugins
[plugin_type
])))
5540 if (r
!= PLUGIN_RET_OK
)
5541 return r
; // stop here
5544 return PLUGIN_RET_OK
;
5547 static void plugins_done()
5551 ll_reset(loaded_plugins
);
5552 while ((p
= ll_next(loaded_plugins
)))
5556 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5558 struct nsctl request
;
5559 struct nsctl response
;
5560 int type
= unpack_control(&request
, buf
, len
);
5564 if (log_stream
&& config
->debug
>= 4)
5568 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5569 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5573 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5574 dump_control(&request
, log_stream
);
5580 case NSCTL_REQ_LOAD
:
5581 if (request
.argc
!= 1)
5583 response
.type
= NSCTL_RES_ERR
;
5585 response
.argv
[0] = "name of plugin required";
5587 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5589 response
.type
= NSCTL_RES_ERR
;
5591 response
.argv
[0] = !r
5592 ? "plugin already loaded"
5593 : "error loading plugin";
5597 response
.type
= NSCTL_RES_OK
;
5603 case NSCTL_REQ_UNLOAD
:
5604 if (request
.argc
!= 1)
5606 response
.type
= NSCTL_RES_ERR
;
5608 response
.argv
[0] = "name of plugin required";
5610 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5612 response
.type
= NSCTL_RES_ERR
;
5614 response
.argv
[0] = !r
5615 ? "plugin not loaded"
5616 : "plugin not found";
5620 response
.type
= NSCTL_RES_OK
;
5626 case NSCTL_REQ_HELP
:
5627 response
.type
= NSCTL_RES_OK
;
5630 ll_reset(loaded_plugins
);
5631 while ((p
= ll_next(loaded_plugins
)))
5633 char **help
= dlsym(p
, "plugin_control_help");
5634 while (response
.argc
< 0xff && help
&& *help
)
5635 response
.argv
[response
.argc
++] = *help
++;
5640 case NSCTL_REQ_CONTROL
:
5642 struct param_control param
= {
5643 config
->cluster_iam_master
,
5650 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5652 if (r
== PLUGIN_RET_ERROR
)
5654 response
.type
= NSCTL_RES_ERR
;
5656 response
.argv
[0] = param
.additional
5658 : "error returned by plugin";
5660 else if (r
== PLUGIN_RET_NOTMASTER
)
5662 static char msg
[] = "must be run on master: 000.000.000.000";
5664 response
.type
= NSCTL_RES_ERR
;
5666 if (config
->cluster_master_address
)
5668 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5669 response
.argv
[0] = msg
;
5673 response
.argv
[0] = "must be run on master: none elected";
5676 else if (!(param
.response
& NSCTL_RESPONSE
))
5678 response
.type
= NSCTL_RES_ERR
;
5680 response
.argv
[0] = param
.response
5681 ? "unrecognised response value from plugin"
5682 : "unhandled action";
5686 response
.type
= param
.response
;
5688 if (param
.additional
)
5691 response
.argv
[0] = param
.additional
;
5699 response
.type
= NSCTL_RES_ERR
;
5701 response
.argv
[0] = "error unpacking control packet";
5704 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5707 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5711 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5714 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5715 if (log_stream
&& config
->debug
>= 4)
5717 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5718 dump_control(&response
, log_stream
);
5722 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5723 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5728 static tunnelidt
new_tunnel()
5731 for (i
= 1; i
< MAXTUNNEL
; i
++)
5733 if (tunnel
[i
].state
== TUNNELFREE
)
5735 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5736 if (i
> config
->cluster_highest_tunnelid
)
5737 config
->cluster_highest_tunnelid
= i
;
5741 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5746 // We're becoming the master. Do any required setup..
5748 // This is principally telling all the plugins that we're
5749 // now a master, and telling them about all the sessions
5750 // that are active too..
5752 void become_master(void)
5755 static struct event_data d
[RADIUS_FDS
];
5756 struct epoll_event e
;
5758 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5760 // running a bunch of iptables commands is slow and can cause
5761 // the master to drop tunnels on takeover--kludge around the
5762 // problem by forking for the moment (note: race)
5763 if (!fork_and_close())
5765 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5767 if (!session
[s
].opened
) // Not an in-use session.
5770 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5777 for (i
= 0; i
< RADIUS_FDS
; i
++)
5779 d
[i
].type
= FD_TYPE_RADIUS
;
5783 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5787 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5793 if (CLI_HELP_REQUESTED
)
5794 return CLI_HELP_NO_ARGS
;
5797 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5799 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5802 if (!session
[s
].opened
)
5805 idle
= time_now
- session
[s
].last_data
;
5806 idle
/= 5 ; // In multiples of 5 seconds.
5816 for (i
= 0; i
< 63; ++i
)
5818 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5820 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5821 cli_print(cli
, "%d total sessions open.", count
);
5825 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5831 if (CLI_HELP_REQUESTED
)
5832 return CLI_HELP_NO_ARGS
;
5835 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5837 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5840 if (!session
[s
].opened
)
5843 d
= time_now
- session
[s
].opened
;
5846 while (d
> 1 && open
< 32)
5856 for (i
= 0; i
< 30; ++i
)
5858 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5861 cli_print(cli
, "%d total sessions open.", count
);
5867 * This unencodes the AVP using the L2TP secret and the previously
5868 * stored random vector. It overwrites the hidden data with the
5869 * unhidden AVP subformat.
5871 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5877 uint16_t m
= htons(type
);
5879 // Compute initial pad
5881 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5882 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5883 MD5_Update(&ctx
, vector
, vec_len
);
5884 MD5_Final(digest
, &ctx
);
5886 // pointer to last decoded 16 octets
5891 // calculate a new pad based on the last decoded block
5892 if (d
>= sizeof(digest
))
5895 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5896 MD5_Update(&ctx
, last
, sizeof(digest
));
5897 MD5_Final(digest
, &ctx
);
5903 *value
++ ^= digest
[d
++];
5908 int find_filter(char const *name
, size_t len
)
5913 for (i
= 0; i
< MAXFILTER
; i
++)
5915 if (!*ip_filters
[i
].name
)
5923 if (strlen(ip_filters
[i
].name
) != len
)
5926 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5933 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5937 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5938 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5939 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5940 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5941 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5947 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5951 case FILTER_FLAG_OP_ANY
:
5952 return (flags
& sflags
) || (~flags
& cflags
);
5954 case FILTER_FLAG_OP_ALL
:
5955 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5957 case FILTER_FLAG_OP_EST
:
5958 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5964 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5966 uint16_t frag_offset
;
5970 uint16_t src_port
= 0;
5971 uint16_t dst_port
= 0;
5973 ip_filter_rulet
*rule
;
5975 if (len
< 20) // up to end of destination address
5978 if ((*buf
>> 4) != 4) // IPv4
5981 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5983 src_ip
= *(in_addr_t
*) (buf
+ 12);
5984 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5986 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5988 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5989 if (len
< l
+ 4) // ports
5992 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
5993 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
5994 if (proto
== IPPROTO_TCP
)
5996 if (len
< l
+ 14) // flags
5999 flags
= buf
[l
+ 13] & 0x3f;
6003 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6005 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6008 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6009 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6012 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6013 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6018 // layer 4 deny rules are skipped
6019 if (rule
->action
== FILTER_ACTION_DENY
&&
6020 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6028 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6030 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6033 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6036 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6037 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6044 return rule
->action
== FILTER_ACTION_PERMIT
;