3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
11 #include <linux/if_tun.h>
15 #include <net/route.h>
18 #include <netinet/in.h>
19 #include <netinet/ip6.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
29 #include <sys/resource.h>
37 #include <sys/sysinfo.h>
39 #include <linux/netlink.h>
40 #include <linux/rtnetlink.h>
47 #include "constants.h"
57 configt
*config
= NULL
; // all configuration
58 int nlfd
= -1; // netlink socket
59 int tunfd
= -1; // tun interface file handle. (network device)
60 int udpfd
= -1; // UDP file handle
61 int controlfd
= -1; // Control signal handle
62 int clifd
= -1; // Socket listening for CLI connections.
63 int daefd
= -1; // Socket listening for DAE connections.
64 int snoopfd
= -1; // UDP file handle for sending out intercept data
65 int *radfds
= NULL
; // RADIUS requests file handles
66 int rand_fd
= -1; // Random data source
67 int cluster_sockfd
= -1; // Intra-cluster communications socket.
68 int epollfd
= -1; // event polling
69 time_t basetime
= 0; // base clock
70 char hostname
[MAXHOSTNAME
] = ""; // us.
71 static int tunidx
; // ifr_ifindex of tun device
72 int nlseqnum
= 0; // netlink sequence number
73 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
74 static int syslog_log
= 0; // are we logging to syslog
75 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
76 uint32_t last_id
= 0; // Unique ID for radius accounting
78 char guest_users
[10][32]; // Array of guest users
79 int guest_accounts_num
= 0; // Number of guest users
81 // calculated from config->l2tp_mtu
82 uint16_t MRU
= 0; // PPP MRU
83 uint16_t MSS
= 0; // TCP MSS
85 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
86 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
91 } ip_hash
[256]; // Mapping from IP address to session structures.
95 struct ipv6radix
*branch
;
96 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
99 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
100 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
103 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
104 time_t time_now
= 0; // Current time in seconds since epoch.
105 static char time_now_string
[64] = {0}; // Current time as a string.
106 static int time_changed
= 0; // time_now changed
107 char main_quit
= 0; // True if we're in the process of exiting.
108 static char main_reload
= 0; // Re-load pending
109 linked_list
*loaded_plugins
;
110 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
112 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
113 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
115 config_descriptt config_values
[] = {
116 CONFIG("debug", debug
, INT
),
117 CONFIG("log_file", log_filename
, STRING
),
118 CONFIG("pid_file", pid_file
, STRING
),
119 CONFIG("random_device", random_device
, STRING
),
120 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
121 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
122 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
123 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
124 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
125 CONFIG("primary_dns", default_dns1
, IPv4
),
126 CONFIG("secondary_dns", default_dns2
, IPv4
),
127 CONFIG("primary_radius", radiusserver
[0], IPv4
),
128 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
129 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
130 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
131 CONFIG("radius_accounting", radius_accounting
, BOOL
),
132 CONFIG("radius_interim", radius_interim
, INT
),
133 CONFIG("radius_secret", radiussecret
, STRING
),
134 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
135 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
136 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
137 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
138 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
139 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
140 CONFIG("guest_account", guest_user
, STRING
),
141 CONFIG("bind_address", bind_address
, IPv4
),
142 CONFIG("peer_address", peer_address
, IPv4
),
143 CONFIG("send_garp", send_garp
, BOOL
),
144 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
145 CONFIG("throttle_buckets", num_tbfs
, INT
),
146 CONFIG("accounting_dir", accounting_dir
, STRING
),
147 CONFIG("dump_speed", dump_speed
, BOOL
),
148 CONFIG("multi_read_count", multi_read_count
, INT
),
149 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
150 CONFIG("lock_pages", lock_pages
, BOOL
),
151 CONFIG("icmp_rate", icmp_rate
, INT
),
152 CONFIG("packet_limit", max_packets
, INT
),
153 CONFIG("cluster_address", cluster_address
, IPv4
),
154 CONFIG("cluster_interface", cluster_interface
, STRING
),
155 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
156 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
157 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
158 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
159 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
160 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
161 CONFIG("hostname", hostname
, STRING
),
162 CONFIG("nexthop_address", nexthop_address
, IPv4
),
163 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
167 static char *plugin_functions
[] = {
172 "plugin_new_session",
173 "plugin_kill_session",
175 "plugin_radius_response",
176 "plugin_radius_reset",
177 "plugin_radius_account",
178 "plugin_become_master",
179 "plugin_new_session_master",
182 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
184 // Counters for shutdown sessions
185 static sessiont shut_acct
[8192];
186 static sessionidt shut_acct_n
= 0;
188 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
189 bundlet
*bundle
= NULL
; // Array of bundle structures.
190 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
191 sessiont
*session
= NULL
; // Array of session structures.
192 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
193 radiust
*radius
= NULL
; // Array of radius structures.
194 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
195 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
196 static controlt
*controlfree
= 0;
197 struct Tstats
*_statistics
= NULL
;
199 struct Tringbuffer
*ringbuffer
= NULL
;
202 static ssize_t
netlink_send(struct nlmsghdr
*nh
);
203 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
);
204 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
205 static void uncache_ipmap(in_addr_t ip
);
206 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
207 static void free_ip_address(sessionidt s
);
208 static void dump_acct_info(int all
);
209 static void sighup_handler(int sig
);
210 static void shutdown_handler(int sig
);
211 static void sigchild_handler(int sig
);
212 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
213 static void update_config(void);
214 static void read_config_file(void);
215 static void initplugins(void);
216 static int add_plugin(char *plugin_name
);
217 static int remove_plugin(char *plugin_name
);
218 static void plugins_done(void);
219 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
220 static tunnelidt
new_tunnel(void);
221 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
222 static void bundleclear(bundleidt b
);
224 // on slaves, alow BGP to withdraw cleanly before exiting
227 // quit actions (master)
228 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
229 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
231 // return internal time (10ths since process startup), set f if given
232 // as a side-effect sets time_now, and time_changed
233 static clockt
now(double *f
)
237 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
238 if (t
.tv_sec
!= time_now
)
243 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
246 // work out a retry time based on try number
247 // This is a straight bounded exponential backoff.
248 // Maximum re-try time is 32 seconds. (2^5).
249 clockt
backoff(uint8_t try)
251 if (try > 5) try = 5; // max backoff
252 return now(NULL
) + 10 * (1 << try);
257 // Log a debug message. Typically called via the LOG macro
259 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
261 static char message
[65536] = {0};
267 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
268 ringbuffer
->tail
= 0;
269 if (ringbuffer
->tail
== ringbuffer
->head
)
270 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
271 ringbuffer
->head
= 0;
273 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
274 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
275 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
276 va_start(ap
, format
);
277 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
282 if (config
->debug
< level
) return;
284 va_start(ap
, format
);
285 vsnprintf(message
, sizeof(message
), format
, ap
);
288 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
290 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
295 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
298 const uint8_t *d
= data
;
300 if (config
->debug
< level
) return;
302 // No support for _log_hex to syslog
305 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
306 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
308 for (i
= 0; i
< maxsize
; )
310 fprintf(log_stream
, "%4X: ", i
);
311 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
313 fprintf(log_stream
, "%02X ", d
[j
]);
315 fputs(": ", log_stream
);
318 for (; j
< i
+ 16; j
++)
320 fputs(" ", log_stream
);
322 fputs(": ", log_stream
);
325 fputs(" ", log_stream
);
326 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
328 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
329 fputc(d
[j
], log_stream
);
331 fputc('.', log_stream
);
334 fputs(" ", log_stream
);
338 fputs("\n", log_stream
);
342 setbuf(log_stream
, NULL
);
346 // update a counter, accumulating 2^32 wraps
347 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
349 uint32_t new = *counter
+ delta
;
356 // initialise the random generator
357 static void initrandom(char *source
)
359 static char path
[sizeof(config
->random_device
)] = "*undefined*";
361 // reinitialise only if we are forced to do so or if the config has changed
362 if (source
&& !strncmp(path
, source
, sizeof(path
)))
365 // close previous source, if any
374 snprintf(path
, sizeof(path
), "%s", source
);
378 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
380 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
381 path
, strerror(errno
));
386 // fill buffer with random data
387 void random_data(uint8_t *buf
, int len
)
394 n
= read(rand_fd
, buf
, len
);
395 if (n
>= len
) return;
400 LOG(0, 0, 0, "Error reading from random source: %s\n",
403 // fall back to rand()
411 // append missing data
413 // not using the low order bits from the prng stream
414 buf
[n
++] = (rand() >> 4) & 0xff;
419 // This adds it to the routing table, advertises it
420 // via BGP if enabled, and stuffs it into the
421 // 'sessionbyip' cache.
423 // 'ip' must be in _host_ order.
425 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
435 if (!prefixlen
) prefixlen
= 32;
437 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
439 memset(&req
, 0, sizeof(req
));
443 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
444 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
448 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
449 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
452 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
454 req
.rt
.rtm_family
= AF_INET
;
455 req
.rt
.rtm_dst_len
= prefixlen
;
456 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
457 req
.rt
.rtm_protocol
= 42;
458 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
459 req
.rt
.rtm_type
= RTN_UNICAST
;
461 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
463 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
467 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
470 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
471 fmtaddr(htonl(ip
), 0), prefixlen
,
472 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
474 if (netlink_send(&req
.nh
) < 0)
475 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
479 bgp_add_route(htonl(ip
), prefixlen
);
481 bgp_del_route(htonl(ip
), prefixlen
);
484 // Add/Remove the IPs to the 'sessionbyip' cache.
485 // Note that we add the zero address in the case of
486 // a network route. Roll on CIDR.
488 // Note that 's == 0' implies this is the address pool.
489 // We still cache it here, because it will pre-fill
490 // the malloc'ed tree.
494 if (!add
) // Are we deleting a route?
495 s
= 0; // Caching the session as '0' is the same as uncaching.
497 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
502 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
510 char ipv6addr
[INET6_ADDRSTRLEN
];
512 if (!config
->ipv6_prefix
.s6_addr
[0])
514 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
518 memset(&req
, 0, sizeof(req
));
522 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
523 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
527 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
528 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
531 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
533 req
.rt
.rtm_family
= AF_INET6
;
534 req
.rt
.rtm_dst_len
= prefixlen
;
535 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
536 req
.rt
.rtm_protocol
= 42;
537 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
538 req
.rt
.rtm_type
= RTN_UNICAST
;
540 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
541 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
543 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
545 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
547 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
550 if (netlink_send(&req
.nh
) < 0)
551 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
555 bgp_add_route6(ip
, prefixlen
);
557 bgp_del_route6(ip
, prefixlen
);
562 if (!add
) // Are we deleting a route?
563 s
= 0; // Caching the session as '0' is the same as uncaching.
565 cache_ipv6map(ip
, prefixlen
, s
);
572 // Set up netlink socket
573 static void initnetlink(void)
575 struct sockaddr_nl nladdr
;
577 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
580 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
584 memset(&nladdr
, 0, sizeof(nladdr
));
585 nladdr
.nl_family
= AF_NETLINK
;
586 nladdr
.nl_pid
= getpid();
588 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
590 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
595 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
597 struct sockaddr_nl nladdr
;
601 nh
->nlmsg_pid
= getpid();
602 nh
->nlmsg_seq
= ++nlseqnum
;
604 // set kernel address
605 memset(&nladdr
, 0, sizeof(nladdr
));
606 nladdr
.nl_family
= AF_NETLINK
;
608 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
609 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
611 return sendmsg(nlfd
, &msg
, 0);
614 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
616 struct sockaddr_nl nladdr
;
620 // set kernel address
621 memset(&nladdr
, 0, sizeof(nladdr
));
622 nladdr
.nl_family
= AF_NETLINK
;
624 iov
= (struct iovec
){ buf
, len
};
625 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
627 return recvmsg(nlfd
, &msg
, 0);
630 /* adapted from iproute2 */
631 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
633 int len
= RTA_LENGTH(alen
);
636 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
637 rta
->rta_type
= type
;
639 memcpy(RTA_DATA(rta
), data
, alen
);
640 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
643 // messages corresponding to different phases seq number
644 static char *tun_nl_phase_msg
[] = {
646 "getting tun interface index",
647 "setting tun interface parameters",
648 "setting tun IPv4 address",
649 "setting tun LL IPv6 address",
650 "setting tun global IPv6 address",
654 // Set up TUN interface
655 static void inittun(void)
659 memset(&ifr
, 0, sizeof(ifr
));
660 ifr
.ifr_flags
= IFF_TUN
;
662 tunfd
= open(TUNDEVICE
, O_RDWR
);
665 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
669 int flags
= fcntl(tunfd
, F_GETFL
, 0);
670 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
672 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
674 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
677 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
) - 1);
678 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
));
680 tunidx
= if_nametoindex(config
->tundevice
);
683 LOG(0, 0, 0, "Can't get tun interface index\n");
692 struct ifinfomsg ifinfo
;
693 struct ifaddrmsg ifaddr
;
695 char rtdata
[32]; // 32 should be enough
697 uint32_t txqlen
, mtu
;
700 memset(&req
, 0, sizeof(req
));
702 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
703 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
704 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
706 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
707 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
708 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
709 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
711 /* Bump up the qlen to deal with bursts from the network */
713 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
714 /* set MTU to modem MRU */
716 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
718 if (netlink_send(&req
.nh
) < 0)
721 memset(&req
, 0, sizeof(req
));
723 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
724 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
725 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
727 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
728 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
729 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
730 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
732 if (config
->bind_address
)
733 ip
= config
->bind_address
;
735 ip
= 0x01010101; // 1.1.1.1
736 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
738 if (netlink_send(&req
.nh
) < 0)
741 // Only setup IPv6 on the tun device if we have a configured prefix
742 if (config
->ipv6_prefix
.s6_addr
[0]) {
745 memset(&req
, 0, sizeof(req
));
747 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
748 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
749 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
751 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
752 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
753 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
754 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
756 // Link local address is FE80::1
757 memset(&ip6
, 0, sizeof(ip6
));
758 ip6
.s6_addr
[0] = 0xFE;
759 ip6
.s6_addr
[1] = 0x80;
761 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
763 if (netlink_send(&req
.nh
) < 0)
766 memset(&req
, 0, sizeof(req
));
768 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
769 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
770 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
772 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
773 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
774 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
775 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
777 // Global address is prefix::1
778 ip6
= config
->ipv6_prefix
;
780 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
782 if (netlink_send(&req
.nh
) < 0)
786 memset(&req
, 0, sizeof(req
));
788 req
.nh
.nlmsg_type
= NLMSG_DONE
;
789 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
791 if (netlink_send(&req
.nh
) < 0)
794 // if we get an error for seqnum < min_initok_nlseqnum,
795 // we must exit as initialization went wrong
796 if (config
->ipv6_prefix
.s6_addr
[0])
797 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
799 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
805 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
810 static void initudp(void)
813 struct sockaddr_in addr
;
816 memset(&addr
, 0, sizeof(addr
));
817 addr
.sin_family
= AF_INET
;
818 addr
.sin_port
= htons(L2TPPORT
);
819 addr
.sin_addr
.s_addr
= config
->bind_address
;
820 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
821 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
823 int flags
= fcntl(udpfd
, F_GETFL
, 0);
824 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
826 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
828 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
833 memset(&addr
, 0, sizeof(addr
));
834 addr
.sin_family
= AF_INET
;
835 addr
.sin_port
= htons(NSCTL_PORT
);
836 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
837 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
838 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
839 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
841 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
845 // Dynamic Authorization Extensions to RADIUS
846 memset(&addr
, 0, sizeof(addr
));
847 addr
.sin_family
= AF_INET
;
848 addr
.sin_port
= htons(config
->radius_dae_port
);
849 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
850 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
851 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
852 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
854 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
859 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
863 // Find session by IP, < 1 for not found
865 // Confusingly enough, this 'ip' must be
866 // in _network_ order. This being the common
867 // case when looking it up from IP packet headers.
869 // We actually use this cache for two things.
870 // #1. For used IP addresses, this maps to the
871 // session ID that it's used by.
872 // #2. For un-used IP addresses, this maps to the
873 // index into the pool table that contains that
877 static sessionidt
lookup_ipmap(in_addr_t ip
)
879 uint8_t *a
= (uint8_t *) &ip
;
880 union iphash
*h
= ip_hash
;
882 if (!(h
= h
[*a
++].idx
)) return 0;
883 if (!(h
= h
[*a
++].idx
)) return 0;
884 if (!(h
= h
[*a
++].idx
)) return 0;
889 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
891 struct ipv6radix
*curnode
;
894 char ipv6addr
[INET6_ADDRSTRLEN
];
896 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
900 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
902 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
907 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
908 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
915 sessionidt
sessionbyip(in_addr_t ip
)
917 sessionidt s
= lookup_ipmap(ip
);
920 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
926 sessionidt
sessionbyipv6(struct in6_addr ip
)
929 CSTAT(sessionbyipv6
);
931 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
932 (ip
.s6_addr
[0] == 0xFE &&
933 ip
.s6_addr
[1] == 0x80 &&
934 ip
.s6_addr16
[1] == 0 &&
935 ip
.s6_addr16
[2] == 0 &&
936 ip
.s6_addr16
[3] == 0)) {
937 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
939 s
= lookup_ipv6map(ip
);
942 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
949 // Take an IP address in HOST byte order and
950 // add it to the sessionid by IP cache.
952 // (It's actually cached in network order)
954 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
956 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
957 uint8_t *a
= (uint8_t *) &nip
;
958 union iphash
*h
= ip_hash
;
961 for (i
= 0; i
< 3; i
++)
963 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
972 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
975 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
976 // else a map to an ip pool index.
979 static void uncache_ipmap(in_addr_t ip
)
981 cache_ipmap(ip
, 0); // Assign it to the NULL session.
984 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
988 struct ipv6radix
*curnode
;
989 char ipv6addr
[INET6_ADDRSTRLEN
];
991 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
993 bytes
= prefixlen
>> 3;
996 if (curnode
->branch
== NULL
)
998 if (!(curnode
->branch
= calloc(256,
999 sizeof (struct ipv6radix
))))
1002 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1009 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1010 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1014 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1015 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1021 // CLI list to dump current ipcache.
1023 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1025 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1029 if (CLI_HELP_REQUESTED
)
1030 return CLI_HELP_NO_ARGS
;
1032 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1034 for (i
= 0; i
< 256; ++i
)
1040 for (j
= 0; j
< 256; ++j
)
1046 for (k
= 0; k
< 256; ++k
)
1052 for (l
= 0; l
< 256; ++l
)
1057 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1063 cli_print(cli
, "%d entries in cache", count
);
1068 // Find session by username, 0 for not found
1069 // walled garden users aren't authenticated, so the username is
1070 // reasonably useless. Ignore them to avoid incorrect actions
1072 // This is VERY inefficent. Don't call it often. :)
1074 sessionidt
sessionbyuser(char *username
)
1077 CSTAT(sessionbyuser
);
1079 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1081 if (!session
[s
].opened
)
1084 if (session
[s
].walled_garden
)
1085 continue; // Skip walled garden users.
1087 if (!strncmp(session
[s
].user
, username
, 128))
1091 return 0; // Not found.
1094 void send_garp(in_addr_t ip
)
1100 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1103 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1106 memset(&ifr
, 0, sizeof(ifr
));
1107 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1108 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1110 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1114 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1115 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1117 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1122 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1125 static sessiont
*sessiontbysessionidt(sessionidt s
)
1127 if (!s
|| s
>= MAXSESSION
) return NULL
;
1131 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1133 sessionidt val
= s
-session
;
1134 if (s
< session
|| val
>= MAXSESSION
) return 0;
1138 // actually send a control message for a specific tunnel
1139 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1141 struct sockaddr_in addr
;
1147 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1148 STAT(tunnel_tx_errors
);
1154 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1155 STAT(tunnel_tx_errors
);
1159 memset(&addr
, 0, sizeof(addr
));
1160 addr
.sin_family
= AF_INET
;
1161 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1162 addr
.sin_port
= htons(tunnel
[t
].port
);
1164 // sequence expected, if sequence in message
1165 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1167 // If this is a control message, deal with retries
1170 tunnel
[t
].last
= time_now
; // control message sent
1171 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1174 STAT(tunnel_retries
);
1175 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1179 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1181 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1182 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1183 STAT(tunnel_tx_errors
);
1187 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1188 STAT(tunnel_tx_packets
);
1189 INC_STAT(tunnel_tx_bytes
, l
);
1193 // Tiny helper function to write data to
1194 // the 'tun' device.
1196 int tun_write(uint8_t * data
, int size
)
1198 return write(tunfd
, data
, size
);
1201 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1202 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1204 int d
= (tcp
[12] >> 4) * 4;
1211 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1214 if (tcp
+ d
> buf
+ len
) // short?
1222 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1225 if (mss
+ 2 > data
) return; // short?
1229 if (*opts
== 0) return; // end of options
1230 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1233 opts
+= opts
[1]; // skip over option
1236 if (!mss
) return; // not found
1237 orig
= ntohs(*(uint16_t *) mss
);
1239 if (orig
<= MSS
) return; // mss OK
1241 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1242 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1243 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1244 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1247 *(int16_t *) mss
= htons(MSS
);
1249 // adjust checksum (see rfc1141)
1250 sum
= orig
+ (~MSS
& 0xffff);
1251 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1252 sum
= (sum
& 0xffff) + (sum
>> 16);
1253 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1256 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1260 // Skip the four extra bytes
1272 proto
= ntohs(*(uint16_t *) p
);
1280 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1281 return; // closing session, PPP not processed
1283 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1284 processipin(s
, t
, p
, l
);
1286 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1290 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1291 return; // closing session, PPP not processed
1294 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1295 processipv6in(s
, t
, p
, l
);
1297 else if (proto
== PPPIPCP
)
1299 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1300 processipcp(s
, t
, p
, l
);
1302 else if (proto
== PPPCCP
)
1304 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1305 processccp(s
, t
, p
, l
);
1309 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1313 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1315 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1316 sp
->cout_delta
+= len
;
1318 sp
->last_data
= time_now
;
1320 sess_local
[s
].cout
+= len
; // To send to master..
1321 sess_local
[s
].pout
++;
1324 // process outgoing (to tunnel) IP
1326 static void processipout(uint8_t *buf
, int len
)
1333 uint8_t *data
= buf
; // Keep a copy of the originals.
1336 uint8_t fragbuf
[MAXETHER
+ 20];
1338 CSTAT(processipout
);
1340 if (len
< MIN_IP_SIZE
)
1342 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1343 STAT(tun_rx_errors
);
1346 if (len
>= MAXETHER
)
1348 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1349 STAT(tun_rx_errors
);
1353 // Skip the tun header
1357 // Got an IP header now
1358 if (*(uint8_t *)(buf
) >> 4 != 4)
1360 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1364 ip
= *(uint32_t *)(buf
+ 16);
1365 if (!(s
= sessionbyip(ip
)))
1367 // Is this a packet for a session that doesn't exist?
1368 static int rate
= 0; // Number of ICMP packets we've sent this second.
1369 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1371 if (last
!= time_now
)
1377 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1379 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1380 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1381 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1386 t
= session
[s
].tunnel
;
1387 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1389 LOG(3, s
, t
, "Packet size more than session MRU\n");
1395 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1396 if (config
->max_packets
> 0)
1398 if (sess_local
[s
].last_packet_out
== TIME
)
1400 int max
= config
->max_packets
;
1402 // All packets for throttled sessions are handled by the
1403 // master, so further limit by using the throttle rate.
1404 // A bit of a kludge, since throttle rate is in kbps,
1405 // but should still be generous given our average DSL
1406 // packet size is 200 bytes: a limit of 28kbps equates
1407 // to around 180 packets per second.
1408 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1409 max
= sp
->throttle_out
;
1411 if (++sess_local
[s
].packets_out
> max
)
1413 sess_local
[s
].packets_dropped
++;
1419 if (sess_local
[s
].packets_dropped
)
1421 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1422 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1423 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1424 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1428 sess_local
[s
].last_packet_out
= TIME
;
1429 sess_local
[s
].packets_out
= 1;
1430 sess_local
[s
].packets_dropped
= 0;
1434 // run access-list if any
1435 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1438 // adjust MSS on SYN and SYN,ACK packets with options
1439 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1441 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1442 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1443 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1448 // Are we throttling this session?
1449 if (config
->cluster_iam_master
)
1450 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1452 master_throttle_packet(sp
->tbf_out
, data
, size
);
1456 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1458 // We are walled-gardening this
1459 master_garden_packet(s
, data
, size
);
1463 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1465 // Add on L2TP header
1466 sessionidt members
[MAXBUNDLESES
];
1467 bundleidt bid
= session
[s
].bundle
;
1468 bundlet
*b
= &bundle
[bid
];
1469 uint32_t num_of_links
, nb_opened
;
1472 num_of_links
= b
->num_of_links
;
1474 for (i
= 0;i
< num_of_links
;i
++)
1477 if (session
[s
].ppp
.lcp
== Opened
)
1479 members
[nb_opened
] = s
;
1486 LOG(2, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1490 num_of_links
= nb_opened
;
1491 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1492 s
= members
[b
->current_ses
];
1493 t
= session
[s
].tunnel
;
1496 if ((num_of_links
> 1) && (len
> MINFRAGLEN
))
1498 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1500 //for rotate traffic among the member links
1501 uint32_t divisor
= num_of_links
;
1503 divisor
= divisor
/2 + (divisor
& 1);
1505 // Partition the packet to "num_of_links" fragments
1506 uint32_t fraglen
= len
/ divisor
;
1507 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1508 uint32_t remain
= len
;
1510 // send the first packet
1511 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1513 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1516 update_session_out_stat(s
, sp
, fraglen
);
1519 while (remain
> last_fraglen
)
1521 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1522 s
= members
[b
->current_ses
];
1523 t
= session
[s
].tunnel
;
1525 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1526 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1528 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1529 update_session_out_stat(s
, sp
, fraglen
);
1532 // send the last fragment
1533 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1534 s
= members
[b
->current_ses
];
1535 t
= session
[s
].tunnel
;
1537 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1538 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1540 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1541 update_session_out_stat(s
, sp
, remain
);
1542 if (remain
!= last_fraglen
)
1543 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1547 // Send it as one frame
1548 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1550 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1551 update_session_out_stat(s
, sp
, len
);
1556 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1558 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1559 update_session_out_stat(s
, sp
, len
);
1562 // Snooping this session, send it to intercept box
1563 if (sp
->snoop_ip
&& sp
->snoop_port
)
1564 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1569 // process outgoing (to tunnel) IPv6
1571 static void processipv6out(uint8_t * buf
, int len
)
1577 struct in6_addr ip6
;
1579 uint8_t *data
= buf
; // Keep a copy of the originals.
1582 uint8_t b
[MAXETHER
+ 20];
1584 CSTAT(processipv6out
);
1586 if (len
< MIN_IP_SIZE
)
1588 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1589 STAT(tunnel_tx_errors
);
1592 if (len
>= MAXETHER
)
1594 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1595 STAT(tunnel_tx_errors
);
1599 // Skip the tun header
1603 // Got an IP header now
1604 if (*(uint8_t *)(buf
) >> 4 != 6)
1606 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1610 ip6
= *(struct in6_addr
*)(buf
+24);
1611 s
= sessionbyipv6(ip6
);
1615 ip
= *(uint32_t *)(buf
+ 32);
1616 s
= sessionbyip(ip
);
1621 // Is this a packet for a session that doesn't exist?
1622 static int rate
= 0; // Number of ICMP packets we've sent this second.
1623 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1625 if (last
!= time_now
)
1631 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1633 // FIXME: Should send icmp6 host unreachable
1637 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1639 bundleidt bid
= session
[s
].bundle
;
1640 bundlet
*b
= &bundle
[bid
];
1642 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1643 s
= b
->members
[b
->current_ses
];
1644 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1646 t
= session
[s
].tunnel
;
1648 sp
->last_data
= time_now
;
1650 // FIXME: add DoS prevention/filters?
1654 // Are we throttling this session?
1655 if (config
->cluster_iam_master
)
1656 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1658 master_throttle_packet(sp
->tbf_out
, data
, size
);
1661 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1663 // We are walled-gardening this
1664 master_garden_packet(s
, data
, size
);
1668 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1670 // Add on L2TP header
1672 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1674 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1677 // Snooping this session, send it to intercept box
1678 if (sp
->snoop_ip
&& sp
->snoop_port
)
1679 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1681 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1682 sp
->cout_delta
+= len
;
1686 sess_local
[s
].cout
+= len
; // To send to master..
1687 sess_local
[s
].pout
++;
1691 // Helper routine for the TBF filters.
1692 // Used to send queued data in to the user!
1694 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1699 uint8_t b
[MAXETHER
+ 20];
1701 if (len
< 0 || len
> MAXETHER
)
1703 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1707 // Skip the tun header
1714 t
= session
[s
].tunnel
;
1717 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1719 // Add on L2TP header
1721 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1723 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1726 // Snooping this session.
1727 if (sp
->snoop_ip
&& sp
->snoop_port
)
1728 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1730 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1731 sp
->cout_delta
+= len
;
1735 sess_local
[s
].cout
+= len
; // To send to master..
1736 sess_local
[s
].pout
++;
1739 // add an AVP (16 bit)
1740 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1742 uint16_t l
= (m
? 0x8008 : 0x0008);
1743 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1744 c
->buf16
[c
->length
/2 + 1] = htons(0);
1745 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1746 c
->buf16
[c
->length
/2 + 3] = htons(val
);
1750 // add an AVP (32 bit)
1751 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1753 uint16_t l
= (m
? 0x800A : 0x000A);
1754 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1755 c
->buf16
[c
->length
/2 + 1] = htons(0);
1756 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1757 *(uint32_t *) &c
->buf
[c
->length
+ 6] = htonl(val
);
1761 // add an AVP (string)
1762 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1764 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1765 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1766 c
->buf16
[c
->length
/2 + 1] = htons(0);
1767 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1768 memcpy(&c
->buf
[c
->length
+ 6], val
, strlen(val
));
1769 c
->length
+= 6 + strlen(val
);
1773 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1775 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1776 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1777 c
->buf16
[c
->length
/2 + 1] = htons(0);
1778 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1779 memcpy(&c
->buf
[c
->length
+ 6], val
, len
);
1780 c
->length
+= 6 + len
;
1783 // new control connection
1784 static controlt
*controlnew(uint16_t mtype
)
1788 c
= malloc(sizeof(controlt
));
1792 controlfree
= c
->next
;
1796 c
->buf16
[0] = htons(0xC802); // flags/ver
1798 control16(c
, 0, mtype
, 1);
1802 // send zero block if nothing is waiting
1804 static void controlnull(tunnelidt t
)
1807 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1810 buf
[0] = htons(0xC802); // flags/ver
1811 buf
[1] = htons(12); // length
1812 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1813 buf
[3] = htons(0); // session
1814 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1815 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1816 tunnelsend((uint8_t *)buf
, 12, t
);
1819 // add a control message to a tunnel, and send if within window
1820 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1822 c
->buf16
[1] = htons(c
->length
); // length
1823 c
->buf16
[2] = htons(tunnel
[t
].far
); // tunnel
1824 c
->buf16
[3] = htons(far
); // session
1825 c
->buf16
[4] = htons(tunnel
[t
].ns
); // sequence
1826 tunnel
[t
].ns
++; // advance sequence
1827 // link in message in to queue
1828 if (tunnel
[t
].controlc
)
1829 tunnel
[t
].controle
->next
= c
;
1831 tunnel
[t
].controls
= c
;
1833 tunnel
[t
].controle
= c
;
1834 tunnel
[t
].controlc
++;
1836 // send now if space in window
1837 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1839 tunnel
[t
].try = 0; // first send
1840 tunnelsend(c
->buf
, c
->length
, t
);
1845 // Throttle or Unthrottle a session
1847 // Throttle the data from/to through a session to no more than
1848 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1851 // If either value is -1, the current value is retained for that
1854 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1856 if (!session
[s
].opened
)
1857 return; // No-one home.
1859 if (!*session
[s
].user
)
1860 return; // User not logged in
1864 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1865 if (session
[s
].tbf_in
)
1866 free_tbf(session
[s
].tbf_in
);
1869 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1871 session
[s
].tbf_in
= 0;
1873 session
[s
].throttle_in
= rate_in
;
1878 int bytes
= rate_out
* 1024 / 8;
1879 if (session
[s
].tbf_out
)
1880 free_tbf(session
[s
].tbf_out
);
1883 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1885 session
[s
].tbf_out
= 0;
1887 session
[s
].throttle_out
= rate_out
;
1891 // add/remove filters from session (-1 = no change)
1892 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1894 if (!session
[s
].opened
)
1895 return; // No-one home.
1897 if (!*session
[s
].user
)
1898 return; // User not logged in
1901 if (filter_in
> MAXFILTER
) filter_in
= -1;
1902 if (filter_out
> MAXFILTER
) filter_out
= -1;
1903 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1904 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1908 if (session
[s
].filter_in
)
1909 ip_filters
[session
[s
].filter_in
- 1].used
--;
1912 ip_filters
[filter_in
- 1].used
++;
1914 session
[s
].filter_in
= filter_in
;
1917 if (filter_out
>= 0)
1919 if (session
[s
].filter_out
)
1920 ip_filters
[session
[s
].filter_out
- 1].used
--;
1923 ip_filters
[filter_out
- 1].used
++;
1925 session
[s
].filter_out
= filter_out
;
1929 // start tidy shutdown of session
1930 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1932 int walled_garden
= session
[s
].walled_garden
;
1933 bundleidt b
= session
[s
].bundle
;
1934 //delete routes only for last session in bundle (in case of MPPP)
1935 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1937 CSTAT(sessionshutdown
);
1939 if (!session
[s
].opened
)
1941 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1942 return; // not a live session
1945 if (!session
[s
].die
)
1947 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1948 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1949 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1950 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1953 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1955 // RADIUS Stop message
1956 uint16_t r
= radiusnew(s
);
1959 // stop, if not already trying
1960 if (radius
[r
].state
!= RADIUSSTOP
)
1962 radius
[r
].term_cause
= term_cause
;
1963 radius
[r
].term_msg
= reason
;
1964 radiussend(r
, RADIUSSTOP
);
1968 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1970 // Save counters to dump to accounting file
1971 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1972 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1976 { // IP allocated, clear and unroute
1979 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1981 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
1982 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
1985 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
1986 session
[s
].route
[r
].ip
= 0;
1989 if (session
[s
].ip_pool_index
== -1) // static ip
1991 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1997 // unroute IPv6, if setup
1998 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
1999 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2003 // This session was part of a bundle
2004 bundle
[b
].num_of_links
--;
2005 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2006 if(bundle
[b
].num_of_links
== 0)
2009 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2013 // Adjust the members array to accomodate the new change
2014 uint8_t mem_num
= 0;
2015 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2016 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2019 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2020 if(bundle
[b
].members
[ml
] == s
)
2025 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2026 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2028 // If the killed session is the first of the bundle,
2029 // the new first session must be stored in the cache_ipmap
2030 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2033 sessionidt new_s
= bundle
[b
].members
[0];
2036 // Add the route for this session.
2037 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2042 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2043 ip
= session
[new_s
].route
[r
].ip
;
2045 if (!prefixlen
) prefixlen
= 32;
2046 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2048 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2049 cache_ipmap(i
, new_s
);
2051 cache_ipmap(session
[new_s
].ip
, new_s
);
2054 if (session
[new_s
].ipv6prefixlen
)
2055 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2060 cluster_send_bundle(b
);
2064 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2065 throttle_session(s
, 0, 0);
2069 controlt
*c
= controlnew(14); // sending CDN
2073 buf
[0] = htons(cdn_result
);
2074 buf
[1] = htons(cdn_error
);
2075 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2078 control16(c
, 1, cdn_result
, 1);
2080 control16(c
, 14, s
, 1); // assigned session (our end)
2081 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2084 // update filter refcounts
2085 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2086 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2089 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2090 sess_local
[s
].lcp
.restart
= 0;
2091 sess_local
[s
].ipcp
.restart
= 0;
2092 sess_local
[s
].ipv6cp
.restart
= 0;
2093 sess_local
[s
].ccp
.restart
= 0;
2095 cluster_send_session(s
);
2098 void sendipcp(sessionidt s
, tunnelidt t
)
2100 uint8_t buf
[MAXETHER
];
2104 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2106 if (!session
[s
].unique_id
)
2108 if (!++last_id
) ++last_id
; // skip zero
2109 session
[s
].unique_id
= last_id
;
2112 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2116 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2117 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2118 q
[4] = 3; // ip address option
2119 q
[5] = 6; // option length
2120 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2121 config
->bind_address
? config
->bind_address
:
2122 my_address
; // send my IP
2124 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2125 restart_timer(s
, ipcp
);
2128 void sendipv6cp(sessionidt s
, tunnelidt t
)
2130 uint8_t buf
[MAXETHER
];
2134 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2136 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2140 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2141 // only send one type
2143 *(uint16_t *) (q
+ 2) = htons(14);
2144 q
[4] = 1; // interface identifier option
2145 q
[5] = 10; // option length
2146 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2147 *(uint32_t *) (q
+ 10) = 0;
2150 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2151 restart_timer(s
, ipv6cp
);
2154 static void sessionclear(sessionidt s
)
2156 memset(&session
[s
], 0, sizeof(session
[s
]));
2157 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2158 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2160 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2161 session
[s
].next
= sessionfree
;
2165 // kill a session now
2166 void sessionkill(sessionidt s
, char *reason
)
2170 if (!session
[s
].opened
) // not alive
2173 if (session
[s
].next
)
2175 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2179 if (!session
[s
].die
)
2180 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2182 if (sess_local
[s
].radius
)
2183 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2185 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2187 cluster_send_session(s
);
2190 static void tunnelclear(tunnelidt t
)
2193 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2194 tunnel
[t
].state
= TUNNELFREE
;
2197 static void bundleclear(bundleidt b
)
2200 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2201 bundle
[b
].state
= BUNDLEFREE
;
2204 // kill a tunnel now
2205 static void tunnelkill(tunnelidt t
, char *reason
)
2212 tunnel
[t
].state
= TUNNELDIE
;
2214 // free control messages
2215 while ((c
= tunnel
[t
].controls
))
2217 controlt
* n
= c
->next
;
2218 tunnel
[t
].controls
= n
;
2219 tunnel
[t
].controlc
--;
2220 c
->next
= controlfree
;
2224 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2225 if (session
[s
].tunnel
== t
)
2226 sessionkill(s
, reason
);
2230 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2231 cli_tunnel_actions
[t
].action
= 0;
2232 cluster_send_tunnel(t
);
2235 // shut down a tunnel cleanly
2236 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2240 CSTAT(tunnelshutdown
);
2242 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2244 // never set up, can immediately kill
2245 tunnelkill(t
, reason
);
2248 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2251 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2252 if (session
[s
].tunnel
== t
)
2253 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2255 tunnel
[t
].state
= TUNNELDIE
;
2256 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2257 cluster_send_tunnel(t
);
2258 // TBA - should we wait for sessions to stop?
2261 controlt
*c
= controlnew(4); // sending StopCCN
2266 buf
[0] = htons(result
);
2267 buf
[1] = htons(error
);
2270 int m
= strlen(msg
);
2271 if (m
+ 4 > sizeof(buf
))
2272 m
= sizeof(buf
) - 4;
2274 memcpy(buf
+2, msg
, m
);
2278 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2281 control16(c
, 1, result
, 1);
2283 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2284 controladd(c
, 0, t
); // send the message
2288 // read and process packet on tunnel (UDP)
2289 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2291 uint8_t *chapresponse
= NULL
;
2292 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2293 uint8_t *p
= buf
+ 2;
2300 LOG_HEX(5, "UDP Data", buf
, len
);
2301 STAT(tunnel_rx_packets
);
2302 INC_STAT(tunnel_rx_bytes
, len
);
2305 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2306 STAT(tunnel_rx_errors
);
2309 if ((buf
[1] & 0x0F) != 2)
2311 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2312 STAT(tunnel_rx_errors
);
2317 l
= ntohs(*(uint16_t *) p
);
2320 t
= ntohs(*(uint16_t *) p
);
2322 s
= ntohs(*(uint16_t *) p
);
2324 if (s
>= MAXSESSION
)
2326 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2327 STAT(tunnel_rx_errors
);
2332 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2333 STAT(tunnel_rx_errors
);
2338 ns
= ntohs(*(uint16_t *) p
);
2340 nr
= ntohs(*(uint16_t *) p
);
2345 uint16_t o
= ntohs(*(uint16_t *) p
);
2350 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2351 STAT(tunnel_rx_errors
);
2356 // used to time out old tunnels
2357 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2358 tunnel
[t
].lastrec
= time_now
;
2362 uint16_t message
= 0xFFFF; // message type
2364 uint8_t mandatory
= 0;
2365 uint16_t asession
= 0; // assigned session
2366 uint32_t amagic
= 0; // magic number
2367 uint8_t aflags
= 0; // flags from last LCF
2368 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2369 char called
[MAXTEL
] = ""; // called number
2370 char calling
[MAXTEL
] = ""; // calling number
2372 if (!config
->cluster_iam_master
)
2374 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2378 // control messages must have bits 0x80|0x40|0x08
2379 // (type, length and sequence) set, and bits 0x02|0x01
2380 // (offset and priority) clear
2381 if ((*buf
& 0xCB) != 0xC8)
2383 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2384 STAT(tunnel_rx_errors
);
2388 // check for duplicate tunnel open message
2394 // Is this a duplicate of the first packet? (SCCRQ)
2396 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2398 if (tunnel
[i
].state
!= TUNNELOPENING
||
2399 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2400 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2403 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2408 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2409 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2411 // if no tunnel specified, assign one
2414 if (!(t
= new_tunnel()))
2416 LOG(1, 0, 0, "No more tunnels\n");
2417 STAT(tunnel_overflow
);
2421 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2422 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2423 tunnel
[t
].window
= 4; // default window
2424 STAT(tunnel_created
);
2425 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2426 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2429 // If the 'ns' just received is not the 'nr' we're
2430 // expecting, just send an ack and drop it.
2432 // if 'ns' is less, then we got a retransmitted packet.
2433 // if 'ns' is greater than missed a packet. Either way
2434 // we should ignore it.
2435 if (ns
!= tunnel
[t
].nr
)
2437 // is this the sequence we were expecting?
2438 STAT(tunnel_rx_errors
);
2439 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2440 t
, ns
, tunnel
[t
].nr
);
2442 if (l
) // Is this not a ZLB?
2447 // check sequence of this message
2449 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2450 // some to clear maybe?
2451 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2453 controlt
*c
= tunnel
[t
].controls
;
2454 tunnel
[t
].controls
= c
->next
;
2455 tunnel
[t
].controlc
--;
2456 c
->next
= controlfree
;
2459 tunnel
[t
].try = 0; // we have progress
2462 // receiver advance (do here so quoted correctly in any sends below)
2463 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2464 if (skip
< 0) skip
= 0;
2465 if (skip
< tunnel
[t
].controlc
)
2467 // some control packets can now be sent that were previous stuck out of window
2468 int tosend
= tunnel
[t
].window
- skip
;
2469 controlt
*c
= tunnel
[t
].controls
;
2477 tunnel
[t
].try = 0; // first send
2478 tunnelsend(c
->buf
, c
->length
, t
);
2483 if (!tunnel
[t
].controlc
)
2484 tunnel
[t
].retry
= 0; // caught up
2487 { // if not a null message
2492 // Default disconnect cause/message on receipt of CDN. Set to
2493 // more specific value from attribute 1 (result code) or 46
2494 // (disconnect cause) if present below.
2495 int disc_cause_set
= 0;
2496 int disc_cause
= TERM_NAS_REQUEST
;
2497 char const *disc_reason
= "Closed (Received CDN).";
2500 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2502 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2509 LOG(1, s
, t
, "Invalid length in AVP\n");
2510 STAT(tunnel_rx_errors
);
2515 if (flags
& 0x3C) // reserved bits, should be clear
2517 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2519 result
= 2; // general error
2520 error
= 3; // reserved field non-zero
2525 if (*(uint16_t *) (b
))
2527 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2529 result
= 2; // general error
2530 error
= 6; // generic vendor-specific error
2531 msg
= "unsupported vendor-specific";
2535 mtype
= ntohs(*(uint16_t *) (b
));
2543 // handle hidden AVPs
2544 if (!*config
->l2tp_secret
)
2546 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2548 result
= 2; // general error
2549 error
= 6; // generic vendor-specific error
2550 msg
= "secret not specified";
2553 if (!session
[s
].random_vector_length
)
2555 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2557 result
= 2; // general error
2558 error
= 6; // generic
2559 msg
= "no random vector";
2564 LOG(2, s
, t
, "Short hidden AVP.\n");
2566 result
= 2; // general error
2567 error
= 2; // length is wrong
2573 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2575 orig_len
= ntohs(*(uint16_t *) b
);
2576 if (orig_len
> n
+ 2)
2578 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2582 result
= 2; // general error
2583 error
= 2; // length is wrong
2592 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2593 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2597 case 0: // message type
2598 message
= ntohs(*(uint16_t *) b
);
2599 mandatory
= flags
& 0x80;
2600 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2602 case 1: // result code
2604 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2605 char const *resdesc
= "(unknown)";
2606 char const *errdesc
= NULL
;
2611 resdesc
= l2tp_stopccn_result_code(rescode
);
2612 cause
= TERM_LOST_SERVICE
;
2614 else if (message
== 14)
2616 resdesc
= l2tp_cdn_result_code(rescode
);
2618 cause
= TERM_LOST_CARRIER
;
2620 cause
= TERM_ADMIN_RESET
;
2623 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2626 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2627 errdesc
= l2tp_error_code(errcode
);
2628 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2631 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2633 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2635 disc_cause_set
= mtype
;
2636 disc_reason
= errdesc
? errdesc
: resdesc
;
2643 case 2: // protocol version
2645 version
= ntohs(*(uint16_t *) (b
));
2646 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2647 if (version
&& version
!= 0x0100)
2648 { // allow 0.0 and 1.0
2649 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2651 result
= 5; // unspported protocol version
2652 error
= 0x0100; // supported version
2658 case 3: // framing capabilities
2660 case 4: // bearer capabilities
2662 case 5: // tie breaker
2663 // We never open tunnels, so we don't care about tie breakers
2665 case 6: // firmware revision
2667 case 7: // host name
2668 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2669 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2670 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2671 // TBA - to send to RADIUS
2673 case 8: // vendor name
2674 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2675 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2676 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2678 case 9: // assigned tunnel
2679 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2680 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2682 case 10: // rx window
2683 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2684 if (!tunnel
[t
].window
)
2685 tunnel
[t
].window
= 1; // window of 0 is silly
2686 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2688 case 11: // Challenge
2690 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2691 build_chap_response(b
, 2, n
, &chapresponse
);
2694 case 13: // Response
2695 // Why did they send a response? We never challenge.
2696 LOG(2, s
, t
, " received unexpected challenge response\n");
2699 case 14: // assigned session
2700 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2701 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2703 case 15: // call serial number
2704 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2706 case 18: // bearer type
2707 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2710 case 19: // framing type
2711 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2714 case 21: // called number
2715 memset(called
, 0, sizeof(called
));
2716 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2717 LOG(4, s
, t
, " Called <%s>\n", called
);
2719 case 22: // calling number
2720 memset(calling
, 0, sizeof(calling
));
2721 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2722 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2726 case 24: // tx connect speed
2729 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2733 // AS5300s send connect speed as a string
2735 memset(tmp
, 0, sizeof(tmp
));
2736 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2737 session
[s
].tx_connect_speed
= atol(tmp
);
2739 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2741 case 38: // rx connect speed
2744 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2748 // AS5300s send connect speed as a string
2750 memset(tmp
, 0, sizeof(tmp
));
2751 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2752 session
[s
].rx_connect_speed
= atol(tmp
);
2754 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2756 case 25: // Physical Channel ID
2758 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2759 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2762 case 29: // Proxy Authentication Type
2764 uint16_t atype
= ntohs(*(uint16_t *)b
);
2765 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2768 case 30: // Proxy Authentication Name
2771 memset(authname
, 0, sizeof(authname
));
2772 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2773 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2777 case 31: // Proxy Authentication Challenge
2779 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2782 case 32: // Proxy Authentication ID
2784 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2785 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2788 case 33: // Proxy Authentication Response
2789 LOG(4, s
, t
, " Proxy Auth Response\n");
2791 case 27: // last sent lcp
2792 { // find magic number
2793 uint8_t *p
= b
, *e
= p
+ n
;
2794 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2796 if (*p
== 5 && p
[1] == 6) // Magic-Number
2797 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2798 else if (*p
== 7) // Protocol-Field-Compression
2799 aflags
|= SESSION_PFC
;
2800 else if (*p
== 8) // Address-and-Control-Field-Compression
2801 aflags
|= SESSION_ACFC
;
2806 case 28: // last recv lcp confreq
2808 case 26: // Initial Received LCP CONFREQ
2810 case 39: // seq required - we control it as an LNS anyway...
2812 case 36: // Random Vector
2813 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2814 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2815 if (n
> sizeof(session
[s
].random_vector
))
2816 n
= sizeof(session
[s
].random_vector
);
2817 memcpy(session
[s
].random_vector
, b
, n
);
2818 session
[s
].random_vector_length
= n
;
2820 case 46: // ppp disconnect cause
2823 uint16_t code
= ntohs(*(uint16_t *) b
);
2824 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2825 uint8_t dir
= *(b
+ 4);
2827 LOG(4, s
, t
, " PPP disconnect cause "
2828 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2829 code
, proto
, dir
, n
- 5, b
+ 5);
2831 disc_cause_set
= mtype
;
2835 case 1: // admin disconnect
2836 disc_cause
= TERM_ADMIN_RESET
;
2837 disc_reason
= "Administrative disconnect";
2839 case 3: // lcp terminate
2840 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2841 disc_cause
= TERM_USER_REQUEST
;
2842 disc_reason
= "Normal disconnection";
2844 case 4: // compulsory encryption unavailable
2845 if (dir
!= 1) break; // 1=refused by peer, 2=local
2846 disc_cause
= TERM_USER_ERROR
;
2847 disc_reason
= "Compulsory encryption refused";
2849 case 5: // lcp: fsm timeout
2850 disc_cause
= TERM_PORT_ERROR
;
2851 disc_reason
= "LCP: FSM timeout";
2853 case 6: // lcp: no recognisable lcp packets received
2854 disc_cause
= TERM_PORT_ERROR
;
2855 disc_reason
= "LCP: no recognisable LCP packets";
2857 case 7: // lcp: magic-no error (possibly looped back)
2858 disc_cause
= TERM_PORT_ERROR
;
2859 disc_reason
= "LCP: magic-no error (possible loop)";
2861 case 8: // lcp: echo request timeout
2862 disc_cause
= TERM_PORT_ERROR
;
2863 disc_reason
= "LCP: echo request timeout";
2865 case 13: // auth: fsm timeout
2866 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2867 disc_reason
= "Authentication: FSM timeout";
2869 case 15: // auth: unacceptable auth protocol
2870 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2871 disc_reason
= "Unacceptable authentication protocol";
2873 case 16: // auth: authentication failed
2874 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2875 disc_reason
= "Authentication failed";
2877 case 17: // ncp: fsm timeout
2878 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2879 disc_reason
= "NCP: FSM timeout";
2881 case 18: // ncp: no ncps available
2882 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2883 disc_reason
= "NCP: no NCPs available";
2885 case 19: // ncp: failure to converge on acceptable address
2886 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2887 disc_reason
= (dir
== 1)
2888 ? "NCP: too many Configure-Naks received from peer"
2889 : "NCP: too many Configure-Naks sent to peer";
2891 case 20: // ncp: user not permitted to use any address
2892 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2893 disc_reason
= (dir
== 1)
2894 ? "NCP: local link address not acceptable to peer"
2895 : "NCP: remote link address not acceptable";
2902 static char e
[] = "unknown AVP 0xXXXX";
2903 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2905 result
= 2; // general error
2906 error
= 8; // unknown mandatory AVP
2907 sprintf((msg
= e
) + 14, "%04x", mtype
);
2914 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2918 case 1: // SCCRQ - Start Control Connection Request
2919 tunnel
[t
].state
= TUNNELOPENING
;
2920 if (main_quit
!= QUIT_SHUTDOWN
)
2922 controlt
*c
= controlnew(2); // sending SCCRP
2923 control16(c
, 2, version
, 1); // protocol version
2924 control32(c
, 3, 3, 1); // framing
2925 controls(c
, 7, hostname
, 1); // host name
2926 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2927 control16(c
, 9, t
, 1); // assigned tunnel
2928 controladd(c
, 0, t
); // send the resply
2932 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2936 tunnel
[t
].state
= TUNNELOPEN
;
2937 tunnel
[t
].lastrec
= time_now
;
2940 tunnel
[t
].state
= TUNNELOPEN
;
2941 tunnel
[t
].lastrec
= time_now
;
2942 controlnull(t
); // ack
2945 controlnull(t
); // ack
2946 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2949 controlnull(t
); // simply ACK
2961 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2963 controlt
*c
= controlnew(11); // ICRP
2966 sessionfree
= session
[s
].next
;
2967 memset(&session
[s
], 0, sizeof(session
[s
]));
2969 if (s
> config
->cluster_highest_sessionid
)
2970 config
->cluster_highest_sessionid
= s
;
2972 session
[s
].opened
= time_now
;
2973 session
[s
].tunnel
= t
;
2974 session
[s
].far
= asession
;
2975 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2976 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2977 control16(c
, 14, s
, 1); // assigned session
2978 controladd(c
, asession
, t
); // send the reply
2980 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2981 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2983 session
[s
].ppp
.phase
= Establish
;
2984 session
[s
].ppp
.lcp
= Starting
;
2986 STAT(session_created
);
2991 controlt
*c
= controlnew(14); // CDN
2994 STAT(session_overflow
);
2995 LOG(1, 0, t
, "No free sessions\n");
2996 control16(c
, 1, 4, 0); // temporary lack of resources
2999 control16(c
, 1, 2, 7); // shutting down, try another
3001 controladd(c
, asession
, t
); // send the message
3008 if (amagic
== 0) amagic
= time_now
;
3009 session
[s
].magic
= amagic
; // set magic number
3010 session
[s
].flags
= aflags
; // set flags received
3011 session
[s
].mru
= PPPoE_MRU
; // default
3012 controlnull(t
); // ack
3015 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3016 sess_local
[s
].ppp_mru
= MRU
;
3018 // Set multilink options before sending initial LCP packet
3019 sess_local
[s
].mp_mrru
= 1614;
3020 sess_local
[s
].mp_epdis
= ntohl(config
->bind_address
? config
->bind_address
: my_address
);
3023 change_state(s
, lcp
, RequestSent
);
3027 controlnull(t
); // ack
3028 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3031 LOG(1, s
, t
, "Missing message type\n");
3034 STAT(tunnel_rx_errors
);
3036 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3038 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3041 if (chapresponse
) free(chapresponse
);
3042 cluster_send_tunnel(t
);
3046 LOG(4, s
, t
, " Got a ZLB ack\n");
3053 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3054 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3055 { // HDLC address header, discard
3061 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3062 STAT(tunnel_rx_errors
);
3072 proto
= ntohs(*(uint16_t *) p
);
3077 if (s
&& !session
[s
].opened
) // Is something wrong??
3079 if (!config
->cluster_iam_master
)
3081 // Pass it off to the master to deal with..
3082 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3087 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3088 STAT(tunnel_rx_errors
);
3092 if (proto
== PPPPAP
)
3094 session
[s
].last_packet
= time_now
;
3095 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3096 processpap(s
, t
, p
, l
);
3098 else if (proto
== PPPCHAP
)
3100 session
[s
].last_packet
= time_now
;
3101 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3102 processchap(s
, t
, p
, l
);
3104 else if (proto
== PPPLCP
)
3106 session
[s
].last_packet
= time_now
;
3107 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3108 processlcp(s
, t
, p
, l
);
3110 else if (proto
== PPPIPCP
)
3112 session
[s
].last_packet
= time_now
;
3113 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3114 processipcp(s
, t
, p
, l
);
3116 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3118 session
[s
].last_packet
= time_now
;
3119 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3120 processipv6cp(s
, t
, p
, l
);
3122 else if (proto
== PPPCCP
)
3124 session
[s
].last_packet
= time_now
;
3125 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3126 processccp(s
, t
, p
, l
);
3128 else if (proto
== PPPIP
)
3132 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3133 return; // closing session, PPP not processed
3136 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3137 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3139 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3143 processipin(s
, t
, p
, l
);
3145 else if (proto
== PPPMP
)
3149 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3150 return; // closing session, PPP not processed
3153 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3154 if (!config
->cluster_iam_master
)
3156 // The fragments reconstruction is managed by the Master.
3157 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3161 processmpin(s
, t
, p
, l
);
3163 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3167 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3168 return; // closing session, PPP not processed
3171 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3172 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3174 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3178 processipv6in(s
, t
, p
, l
);
3180 else if (session
[s
].ppp
.lcp
== Opened
)
3182 session
[s
].last_packet
= time_now
;
3183 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3184 protoreject(s
, t
, p
, l
, proto
);
3188 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3189 proto
, ppp_state(session
[s
].ppp
.lcp
));
3194 // read and process packet on tun
3195 static void processtun(uint8_t * buf
, int len
)
3197 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3198 STAT(tun_rx_packets
);
3199 INC_STAT(tun_rx_bytes
, len
);
3207 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3208 STAT(tun_rx_errors
);
3212 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3213 processipout(buf
, len
);
3214 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3215 && config
->ipv6_prefix
.s6_addr
[0])
3216 processipv6out(buf
, len
);
3221 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3222 // that we look at the whole of the tunnel, radius and session tables
3224 static void regular_cleanups(double period
)
3226 // Next tunnel, radius and session to check for actions on.
3227 static tunnelidt t
= 0;
3229 static sessionidt s
= 0;
3242 // divide up tables into slices based on the last run
3243 t_slice
= config
->cluster_highest_tunnelid
* period
;
3244 r_slice
= (MAXRADIUS
- 1) * period
;
3245 s_slice
= config
->cluster_highest_sessionid
* period
;
3249 else if (t_slice
> config
->cluster_highest_tunnelid
)
3250 t_slice
= config
->cluster_highest_tunnelid
;
3254 else if (r_slice
> (MAXRADIUS
- 1))
3255 r_slice
= MAXRADIUS
- 1;
3259 else if (s_slice
> config
->cluster_highest_sessionid
)
3260 s_slice
= config
->cluster_highest_sessionid
;
3262 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3264 for (i
= 0; i
< t_slice
; i
++)
3267 if (t
> config
->cluster_highest_tunnelid
)
3270 // check for expired tunnels
3271 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3273 STAT(tunnel_timeout
);
3274 tunnelkill(t
, "Expired");
3278 // check for message resend
3279 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3281 // resend pending messages as timeout on reply
3282 if (tunnel
[t
].retry
<= TIME
)
3284 controlt
*c
= tunnel
[t
].controls
;
3285 uint16_t w
= tunnel
[t
].window
;
3286 tunnel
[t
].try++; // another try
3287 if (tunnel
[t
].try > 5)
3288 tunnelkill(t
, "Timeout on control message"); // game over
3292 tunnelsend(c
->buf
, c
->length
, t
);
3300 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3302 controlt
*c
= controlnew(6); // sending HELLO
3303 controladd(c
, 0, t
); // send the message
3304 LOG(3, 0, t
, "Sending HELLO message\n");
3308 // Check for tunnel changes requested from the CLI
3309 if ((a
= cli_tunnel_actions
[t
].action
))
3311 cli_tunnel_actions
[t
].action
= 0;
3312 if (a
& CLI_TUN_KILL
)
3314 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3315 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3321 for (i
= 0; i
< r_slice
; i
++)
3327 if (!radius
[r
].state
)
3330 if (radius
[r
].retry
<= TIME
)
3337 for (i
= 0; i
< s_slice
; i
++)
3340 if (s
> config
->cluster_highest_sessionid
)
3343 if (!session
[s
].opened
) // Session isn't in use
3346 // check for expired sessions
3349 if (session
[s
].die
<= TIME
)
3351 sessionkill(s
, "Expired");
3358 if (sess_local
[s
].lcp
.restart
<= time_now
)
3360 int next_state
= session
[s
].ppp
.lcp
;
3361 switch (session
[s
].ppp
.lcp
)
3365 next_state
= RequestSent
;
3368 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3370 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3371 sendlcp(s
, session
[s
].tunnel
);
3372 change_state(s
, lcp
, next_state
);
3376 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3377 STAT(session_timeout
);
3387 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3389 int next_state
= session
[s
].ppp
.ipcp
;
3390 switch (session
[s
].ppp
.ipcp
)
3394 next_state
= RequestSent
;
3397 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3399 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3400 sendipcp(s
, session
[s
].tunnel
);
3401 change_state(s
, ipcp
, next_state
);
3405 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3406 STAT(session_timeout
);
3416 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3418 int next_state
= session
[s
].ppp
.ipv6cp
;
3419 switch (session
[s
].ppp
.ipv6cp
)
3423 next_state
= RequestSent
;
3426 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3428 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3429 sendipv6cp(s
, session
[s
].tunnel
);
3430 change_state(s
, ipv6cp
, next_state
);
3434 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3435 change_state(s
, ipv6cp
, Stopped
);
3442 if (sess_local
[s
].ccp
.restart
<= time_now
)
3444 int next_state
= session
[s
].ppp
.ccp
;
3445 switch (session
[s
].ppp
.ccp
)
3449 next_state
= RequestSent
;
3452 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3454 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3455 sendccp(s
, session
[s
].tunnel
);
3456 change_state(s
, ccp
, next_state
);
3460 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3461 change_state(s
, ccp
, Stopped
);
3468 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3469 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3471 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3472 STAT(session_timeout
);
3477 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3478 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3479 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3481 uint8_t b
[MAXETHER
];
3483 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3487 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3488 *(uint16_t *)(q
+ 2) = htons(8); // Length
3489 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3491 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3492 (int)(time_now
- session
[s
].last_packet
));
3493 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3494 sess_local
[s
].last_echo
= time_now
;
3498 // Drop sessions who have reached session_timeout seconds
3499 if (session
[s
].session_timeout
)
3501 bundleidt bid
= session
[s
].bundle
;
3504 if (time_now
- bundle
[bid
].last_check
>= 1)
3506 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3507 bundle
[bid
].last_check
= time_now
;
3508 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3511 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3513 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3520 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3522 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3528 // Drop sessions who have reached idle_timeout seconds
3529 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3531 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3532 STAT(session_timeout
);
3537 // Check for actions requested from the CLI
3538 if ((a
= cli_session_actions
[s
].action
))
3542 cli_session_actions
[s
].action
= 0;
3543 if (a
& CLI_SESS_KILL
)
3545 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3546 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3547 a
= 0; // dead, no need to check for other actions
3551 if (a
& CLI_SESS_NOSNOOP
)
3553 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3554 session
[s
].snoop_ip
= 0;
3555 session
[s
].snoop_port
= 0;
3559 else if (a
& CLI_SESS_SNOOP
)
3561 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3562 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3563 cli_session_actions
[s
].snoop_port
);
3565 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3566 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3571 if (a
& CLI_SESS_NOTHROTTLE
)
3573 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3574 throttle_session(s
, 0, 0);
3578 else if (a
& CLI_SESS_THROTTLE
)
3580 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3581 cli_session_actions
[s
].throttle_in
,
3582 cli_session_actions
[s
].throttle_out
);
3584 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3589 if (a
& CLI_SESS_NOFILTER
)
3591 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3592 filter_session(s
, 0, 0);
3596 else if (a
& CLI_SESS_FILTER
)
3598 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3599 cli_session_actions
[s
].filter_in
,
3600 cli_session_actions
[s
].filter_out
);
3602 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3608 cluster_send_session(s
);
3611 // RADIUS interim accounting
3612 if (config
->radius_accounting
&& config
->radius_interim
> 0
3613 && session
[s
].ip
&& !session
[s
].walled_garden
3614 && !sess_local
[s
].radius
// RADIUS already in progress
3615 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3616 && session
[s
].flags
& SESSION_STARTED
)
3618 int rad
= radiusnew(s
);
3621 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3622 STAT(radius_overflow
);
3626 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3627 session
[s
].user
, session
[s
].unique_id
);
3629 radiussend(rad
, RADIUSINTERIM
);
3630 sess_local
[s
].last_interim
= time_now
;
3635 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3636 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3640 // Are we in the middle of a tunnel update, or radius
3643 static int still_busy(void)
3646 static clockt last_talked
= 0;
3647 static clockt start_busy_wait
= 0;
3650 static time_t stopped_bgp
= 0;
3655 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3657 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3658 if (bgp_peers
[i
].state
== Established
)
3659 bgp_stop(&bgp_peers
[i
]);
3661 stopped_bgp
= time_now
;
3663 if (!config
->cluster_iam_master
)
3665 // we don't want to become master
3666 cluster_send_ping(0);
3672 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3677 if (!config
->cluster_iam_master
)
3680 if (main_quit
== QUIT_SHUTDOWN
)
3682 static int dropped
= 0;
3687 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3688 for (i
= 1; i
< MAXTUNNEL
; i
++)
3689 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3690 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3696 if (start_busy_wait
== 0)
3697 start_busy_wait
= TIME
;
3699 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3701 if (!tunnel
[i
].controlc
)
3704 if (last_talked
!= TIME
)
3706 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3712 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3713 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3715 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3719 for (i
= 1; i
< MAXRADIUS
; i
++)
3721 if (radius
[i
].state
== RADIUSNULL
)
3723 if (radius
[i
].state
== RADIUSWAIT
)
3726 if (last_talked
!= TIME
)
3728 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3738 # include <sys/epoll.h>
3740 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3741 # include "fake_epoll.h"
3744 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3747 // additional polled fds
3749 # define EXTRA_FDS BGP_NUM_PEERS
3751 # define EXTRA_FDS 0
3754 // main loop - gets packets on tun or udp and processes them
3755 static void mainloop(void)
3759 clockt next_cluster_ping
= 0; // send initial ping immediately
3760 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3761 int maxevent
= sizeof(events
)/sizeof(*events
);
3763 if ((epollfd
= epoll_create(maxevent
)) < 0)
3765 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3769 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3770 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3772 /* setup our fds to poll for input */
3774 static struct event_data d
[BASE_FDS
];
3775 struct epoll_event e
;
3782 d
[i
].type
= FD_TYPE_CLI
;
3783 e
.data
.ptr
= &d
[i
++];
3784 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3787 d
[i
].type
= FD_TYPE_CLUSTER
;
3788 e
.data
.ptr
= &d
[i
++];
3789 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3791 d
[i
].type
= FD_TYPE_TUN
;
3792 e
.data
.ptr
= &d
[i
++];
3793 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3795 d
[i
].type
= FD_TYPE_UDP
;
3796 e
.data
.ptr
= &d
[i
++];
3797 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3799 d
[i
].type
= FD_TYPE_CONTROL
;
3800 e
.data
.ptr
= &d
[i
++];
3801 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3803 d
[i
].type
= FD_TYPE_DAE
;
3804 e
.data
.ptr
= &d
[i
++];
3805 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3807 d
[i
].type
= FD_TYPE_NETLINK
;
3808 e
.data
.ptr
= &d
[i
++];
3809 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3813 signal(SIGPIPE
, SIG_IGN
);
3814 bgp_setup(config
->as_number
);
3815 if (config
->bind_address
)
3816 bgp_add_route(config
->bind_address
, 0xffffffff);
3818 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3820 if (config
->neighbour
[i
].name
[0])
3821 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3822 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3823 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
3824 0); /* 0 = routing disabled */
3828 while (!main_quit
|| still_busy())
3838 config
->reload_config
++;
3841 if (config
->reload_config
)
3843 config
->reload_config
= 0;
3851 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3852 STAT(select_called
);
3857 if (errno
== EINTR
||
3858 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3861 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3867 struct sockaddr_in addr
;
3868 struct in_addr local
;
3873 int cluster_ready
= 0;
3876 int cluster_pkts
= 0;
3878 uint32_t bgp_events
[BGP_NUM_PEERS
];
3879 memset(bgp_events
, 0, sizeof(bgp_events
));
3882 for (c
= n
, i
= 0; i
< c
; i
++)
3884 struct event_data
*d
= events
[i
].data
.ptr
;
3888 case FD_TYPE_CLI
: // CLI connections
3892 alen
= sizeof(addr
);
3893 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3899 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3905 // these are handled below, with multiple interleaved reads
3906 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3907 case FD_TYPE_TUN
: tun_ready
++; break;
3908 case FD_TYPE_UDP
: udp_ready
++; break;
3910 case FD_TYPE_CONTROL
: // nsctl commands
3911 alen
= sizeof(addr
);
3912 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3913 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3917 case FD_TYPE_DAE
: // DAE requests
3918 alen
= sizeof(addr
);
3919 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3920 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3924 case FD_TYPE_RADIUS
: // RADIUS response
3925 alen
= sizeof(addr
);
3926 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3927 if (s
>= 0 && config
->cluster_iam_master
)
3929 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3930 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3931 processrad(buf
, s
, d
->index
);
3933 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3934 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3942 bgp_events
[d
->index
] = events
[i
].events
;
3947 case FD_TYPE_NETLINK
:
3949 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
3950 s
= netlink_recv(buf
, sizeof(buf
));
3951 if (nh
->nlmsg_type
== NLMSG_ERROR
)
3953 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
3956 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
3958 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
3963 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
3968 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
);
3974 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3979 bgp_process(bgp_events
);
3982 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3987 alen
= sizeof(addr
);
3988 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3990 processudp(buf
, s
, &addr
);
4003 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
4018 alen
= sizeof(addr
);
4019 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4021 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
4032 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4033 STAT(multi_read_used
);
4035 if (c
>= config
->multi_read_count
)
4037 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
4038 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
4040 STAT(multi_read_exceeded
);
4046 /* no event received, but timers could still have expired */
4047 bgp_process_peers_timers();
4052 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4054 // Log current traffic stats
4055 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4056 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4057 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4058 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4059 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4061 udp_tx
= udp_rx
= 0;
4062 udp_rx_pkt
= eth_rx_pkt
= 0;
4063 eth_tx
= eth_rx
= 0;
4066 if (config
->dump_speed
)
4067 printf("%s\n", config
->bandwidth
);
4069 // Update the internal time counter
4070 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4074 struct param_timer p
= { time_now
};
4075 run_plugins(PLUGIN_TIMER
, &p
);
4079 // Runs on every machine (master and slaves).
4080 if (next_cluster_ping
<= TIME
)
4082 // Check to see which of the cluster is still alive..
4084 cluster_send_ping(basetime
); // Only does anything if we're a slave
4085 cluster_check_master(); // ditto.
4087 cluster_heartbeat(); // Only does anything if we're a master.
4088 cluster_check_slaves(); // ditto.
4090 master_update_counts(); // If we're a slave, send our byte counters to our master.
4092 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4093 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4095 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4098 if (!config
->cluster_iam_master
)
4101 // Run token bucket filtering queue..
4102 // Only run it every 1/10th of a second.
4104 static clockt last_run
= 0;
4105 if (last_run
!= TIME
)
4112 // Handle timeouts, retries etc.
4114 static double last_clean
= 0;
4118 TIME
= now(&this_clean
);
4119 diff
= this_clean
- last_clean
;
4121 // Run during idle time (after we've handled
4122 // all incoming packets) or every 1/10th sec
4123 if (!more
|| diff
> 0.1)
4125 regular_cleanups(diff
);
4126 last_clean
= this_clean
;
4130 if (*config
->accounting_dir
)
4132 static clockt next_acct
= 0;
4133 static clockt next_shut_acct
= 0;
4135 if (next_acct
<= TIME
)
4137 // Dump accounting data
4138 next_acct
= TIME
+ ACCT_TIME
;
4139 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4142 else if (next_shut_acct
<= TIME
)
4144 // Dump accounting data for shutdown sessions
4145 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4152 // Are we the master and shutting down??
4153 if (config
->cluster_iam_master
)
4154 cluster_heartbeat(); // Flush any queued changes..
4156 // Ok. Notify everyone we're shutting down. If we're
4157 // the master, this will force an election.
4158 cluster_send_ping(0);
4161 // Important!!! We MUST not process any packets past this point!
4162 LOG(1, 0, 0, "Shutdown complete\n");
4165 static void stripdomain(char *host
)
4169 if ((p
= strchr(host
, '.')))
4175 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4181 while (fgets(buf
, sizeof(buf
), resolv
))
4183 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4186 if (!isspace(buf
[6]))
4190 while (isspace(*b
)) b
++;
4195 while (*b
&& !isspace(*b
)) b
++;
4197 if (buf
[0] == 'd') // domain is canonical
4203 // first search line
4206 // hold, may be subsequent domain line
4207 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4218 int hl
= strlen(host
);
4219 int dl
= strlen(domain
);
4220 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4221 host
[hl
-dl
- 1] = 0;
4225 *p
= 0; // everything after first dot
4230 // Init data structures
4231 static void initdata(int optdebug
, char *optconfig
)
4235 if (!(config
= shared_malloc(sizeof(configt
))))
4237 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4241 memset(config
, 0, sizeof(configt
));
4242 time(&config
->start_time
);
4243 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4244 config
->debug
= optdebug
;
4245 config
->num_tbfs
= MAXTBFS
;
4246 config
->rl_rate
= 28; // 28kbps
4247 config
->cluster_mcast_ttl
= 1;
4248 config
->cluster_master_min_adv
= 1;
4249 config
->ppp_restart_time
= 3;
4250 config
->ppp_max_configure
= 10;
4251 config
->ppp_max_failure
= 5;
4252 config
->kill_timedout_sessions
= 1;
4253 strcpy(config
->random_device
, RANDOMDEVICE
);
4255 log_stream
= stderr
;
4258 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4260 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4263 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4266 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4268 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4271 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4273 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4276 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4278 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4281 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4283 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4286 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4288 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4292 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4294 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4298 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4300 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4304 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4306 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4310 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4312 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4315 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4317 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4319 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4322 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4324 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4326 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4329 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4331 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4332 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4333 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4334 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4335 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4337 // Put all the sessions on the free list marked as undefined.
4338 for (i
= 1; i
< MAXSESSION
; i
++)
4340 session
[i
].next
= i
+ 1;
4341 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4343 session
[MAXSESSION
- 1].next
= 0;
4346 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4347 for (i
= 1; i
< MAXTUNNEL
; i
++)
4348 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4350 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4351 bundle
[i
].state
= BUNDLEUNDEF
;
4356 // Grab my hostname unless it's been specified
4357 gethostname(hostname
, sizeof(hostname
));
4358 stripdomain(hostname
);
4361 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4364 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4366 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4372 static int assign_ip_address(sessionidt s
)
4376 time_t best_time
= time_now
;
4377 char *u
= session
[s
].user
;
4381 CSTAT(assign_ip_address
);
4383 for (i
= 1; i
< ip_pool_size
; i
++)
4385 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4388 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4395 if (ip_address_pool
[i
].last
< best_time
)
4398 if (!(best_time
= ip_address_pool
[i
].last
))
4399 break; // never used, grab this one
4405 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4409 session
[s
].ip
= ip_address_pool
[best
].address
;
4410 session
[s
].ip_pool_index
= best
;
4411 ip_address_pool
[best
].assigned
= 1;
4412 ip_address_pool
[best
].last
= time_now
;
4413 ip_address_pool
[best
].session
= s
;
4414 if (session
[s
].walled_garden
)
4415 /* Don't track addresses of users in walled garden (note: this
4416 means that their address isn't "sticky" even if they get
4418 ip_address_pool
[best
].user
[0] = 0;
4420 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4423 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4424 reuse
? "Reusing" : "Allocating", best
);
4429 static void free_ip_address(sessionidt s
)
4431 int i
= session
[s
].ip_pool_index
;
4434 CSTAT(free_ip_address
);
4437 return; // what the?
4439 if (i
< 0) // Is this actually part of the ip pool?
4443 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4445 ip_address_pool
[i
].assigned
= 0;
4446 ip_address_pool
[i
].session
= 0;
4447 ip_address_pool
[i
].last
= time_now
;
4451 // Fsck the address pool against the session table.
4452 // Normally only called when we become a master.
4454 // This isn't perfect: We aren't keep tracking of which
4455 // users used to have an IP address.
4457 void rebuild_address_pool(void)
4462 // Zero the IP pool allocation, and build
4463 // a map from IP address to pool index.
4464 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4466 ip_address_pool
[i
].assigned
= 0;
4467 ip_address_pool
[i
].session
= 0;
4468 if (!ip_address_pool
[i
].address
)
4471 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4474 for (i
= 0; i
< MAXSESSION
; ++i
)
4477 if (!(session
[i
].opened
&& session
[i
].ip
))
4480 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4482 if (session
[i
].ip_pool_index
< 0)
4484 // Not allocated out of the pool.
4485 if (ipid
< 1) // Not found in the pool either? good.
4488 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4489 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4491 // Fall through and process it as part of the pool.
4495 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4497 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4499 session
[i
].ip_pool_index
= ipid
;
4503 ip_address_pool
[ipid
].assigned
= 1;
4504 ip_address_pool
[ipid
].session
= i
;
4505 ip_address_pool
[ipid
].last
= time_now
;
4506 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4507 session
[i
].ip_pool_index
= ipid
;
4508 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4513 // Fix the address pool to match a changed session.
4514 // (usually when the master sends us an update).
4515 static void fix_address_pool(int sid
)
4519 ipid
= session
[sid
].ip_pool_index
;
4521 if (ipid
> ip_pool_size
)
4522 return; // Ignore it. rebuild_address_pool will fix it up.
4524 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4525 return; // Just ignore it. rebuild_address_pool will take care of it.
4527 ip_address_pool
[ipid
].assigned
= 1;
4528 ip_address_pool
[ipid
].session
= sid
;
4529 ip_address_pool
[ipid
].last
= time_now
;
4530 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4534 // Add a block of addresses to the IP pool to hand out.
4536 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4540 prefixlen
= 32; // Host route only.
4542 addr
&= 0xffffffff << (32 - prefixlen
);
4544 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4547 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4549 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4550 continue; // Skip 0 and broadcast addresses.
4552 ip_address_pool
[ip_pool_size
].address
= i
;
4553 ip_address_pool
[ip_pool_size
].assigned
= 0;
4555 if (ip_pool_size
>= MAXIPPOOL
)
4557 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4563 // Initialize the IP address pool
4564 static void initippool()
4569 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4571 if (!(f
= fopen(IPPOOLFILE
, "r")))
4573 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4577 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4580 buf
[4095] = 0; // Force it to be zero terminated/
4582 if (*buf
== '#' || *buf
== '\n')
4583 continue; // Skip comments / blank lines
4584 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4585 if ((p
= (char *)strchr(buf
, ':')))
4589 src
= inet_addr(buf
);
4590 if (src
== INADDR_NONE
)
4592 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4595 // This entry is for a specific IP only
4596 if (src
!= config
->bind_address
)
4601 if ((p
= (char *)strchr(pool
, '/')))
4605 in_addr_t start
= 0;
4607 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4609 if (!*p
|| !(numbits
= atoi(p
)))
4611 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4614 start
= ntohl(inet_addr(pool
));
4616 // Add a static route for this pool
4617 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4618 fmtaddr(htonl(start
), 0), numbits
);
4620 routeset(0, start
, numbits
, 0, 1);
4622 add_to_ip_pool(start
, numbits
);
4626 // It's a single ip address
4627 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4631 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4634 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4636 struct sockaddr_in snoop_addr
= {0};
4637 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4640 snoop_addr
.sin_family
= AF_INET
;
4641 snoop_addr
.sin_addr
.s_addr
= destination
;
4642 snoop_addr
.sin_port
= ntohs(port
);
4644 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4645 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4646 htons(snoop_addr
.sin_port
));
4648 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4649 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4651 STAT(packets_snooped
);
4654 static int dump_session(FILE **f
, sessiont
*s
)
4656 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4661 char filename
[1024];
4663 time_t now
= time(NULL
);
4665 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4666 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4668 if (!(*f
= fopen(filename
, "w")))
4670 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4674 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4675 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4680 "# format: username ip qos uptxoctets downrxoctets\n",
4682 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4687 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4688 fprintf(*f
, "%s %s %d %u %u\n",
4689 s
->user
, // username
4690 fmtaddr(htonl(s
->ip
), 0), // ip
4691 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4692 (uint32_t) s
->cin_delta
, // uptxoctets
4693 (uint32_t) s
->cout_delta
); // downrxoctets
4695 s
->cin_delta
= s
->cout_delta
= 0;
4700 static void dump_acct_info(int all
)
4706 CSTAT(dump_acct_info
);
4710 for (i
= 0; i
< shut_acct_n
; i
++)
4711 dump_session(&f
, &shut_acct
[i
]);
4717 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4718 dump_session(&f
, &session
[i
]);
4725 int main(int argc
, char *argv
[])
4729 char *optconfig
= CONFIGFILE
;
4731 time(&basetime
); // start clock
4734 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4739 if (fork()) exit(0);
4741 freopen("/dev/null", "r", stdin
);
4742 freopen("/dev/null", "w", stdout
);
4743 freopen("/dev/null", "w", stderr
);
4752 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4755 printf("Args are:\n"
4756 "\t-d\t\tDetach from terminal\n"
4757 "\t-c <file>\tConfig file\n"
4758 "\t-h <hostname>\tForce hostname\n"
4766 // Start the timer routine off
4768 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4771 initdata(optdebug
, optconfig
);
4775 /* set hostname /after/ having read the config file */
4776 if (*config
->hostname
)
4777 strcpy(hostname
, config
->hostname
);
4778 cli_init_complete(hostname
);
4780 init_tbf(config
->num_tbfs
);
4782 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4783 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4784 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4787 rlim
.rlim_cur
= RLIM_INFINITY
;
4788 rlim
.rlim_max
= RLIM_INFINITY
;
4789 // Remove the maximum core size
4790 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4791 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4793 // Make core dumps go to /tmp
4797 if (config
->scheduler_fifo
)
4800 struct sched_param params
= {0};
4801 params
.sched_priority
= 1;
4803 if (get_nprocs() < 2)
4805 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4806 config
->scheduler_fifo
= 0;
4810 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4812 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4816 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4817 config
->scheduler_fifo
= 0;
4824 /* Set up the cluster communications port. */
4825 if (cluster_init() < 0)
4829 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4837 unsigned seed
= time_now
^ getpid();
4838 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4842 signal(SIGHUP
, sighup_handler
);
4843 signal(SIGCHLD
, sigchild_handler
);
4844 signal(SIGTERM
, shutdown_handler
);
4845 signal(SIGINT
, shutdown_handler
);
4846 signal(SIGQUIT
, shutdown_handler
);
4848 // Prevent us from getting paged out
4849 if (config
->lock_pages
)
4851 if (!mlockall(MCL_CURRENT
))
4852 LOG(1, 0, 0, "Locking pages into memory\n");
4854 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4859 /* remove plugins (so cleanup code gets run) */
4862 // Remove the PID file if we wrote it
4863 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4864 unlink(config
->pid_file
);
4866 /* kill CLI children */
4867 signal(SIGTERM
, SIG_IGN
);
4872 static void sighup_handler(int sig
)
4877 static void shutdown_handler(int sig
)
4879 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4882 static void sigchild_handler(int sig
)
4884 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4888 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4891 *challenge_response
= NULL
;
4893 if (!*config
->l2tp_secret
)
4895 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4899 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4901 *challenge_response
= calloc(17, 1);
4904 MD5_Update(&ctx
, &id
, 1);
4905 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4906 MD5_Update(&ctx
, challenge
, challenge_length
);
4907 MD5_Final(*challenge_response
, &ctx
);
4912 static int facility_value(char *name
)
4915 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4917 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4918 return facilitynames
[i
].c_val
;
4923 static void update_config()
4927 static int timeout
= 0;
4928 static int interval
= 0;
4935 if (log_stream
!= stderr
)
4941 if (*config
->log_filename
)
4943 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4945 char *p
= config
->log_filename
+ 7;
4948 openlog("l2tpns", LOG_PID
, facility_value(p
));
4952 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4954 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4956 fseek(log_stream
, 0, SEEK_END
);
4957 setbuf(log_stream
, NULL
);
4961 log_stream
= stderr
;
4962 setbuf(log_stream
, NULL
);
4968 log_stream
= stderr
;
4969 setbuf(log_stream
, NULL
);
4972 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4973 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4975 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4976 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4977 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4979 // reset MRU/MSS globals
4980 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4981 if (MRU
> PPPoE_MRU
)
4984 MSS
= MRU
- TCP_HDRS
;
4987 config
->numradiusservers
= 0;
4988 for (i
= 0; i
< MAXRADSERVER
; i
++)
4989 if (config
->radiusserver
[i
])
4991 config
->numradiusservers
++;
4992 // Set radius port: if not set, take the port from the
4993 // first radius server. For the first radius server,
4994 // take the #defined default value from l2tpns.h
4996 // test twice, In case someone works with
4997 // a secondary radius server without defining
4998 // a primary one, this will work even then.
4999 if (i
> 0 && !config
->radiusport
[i
])
5000 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5001 if (!config
->radiusport
[i
])
5002 config
->radiusport
[i
] = RADPORT
;
5005 if (!config
->numradiusservers
)
5006 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5008 // parse radius_authtypes_s
5009 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5010 p
= config
->radius_authtypes_s
;
5013 char *s
= strpbrk(p
, " \t,");
5019 while (*s
== ' ' || *s
== '\t')
5026 if (!strncasecmp("chap", p
, strlen(p
)))
5028 else if (!strncasecmp("pap", p
, strlen(p
)))
5031 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5033 config
->radius_authtypes
|= type
;
5034 if (!config
->radius_authprefer
)
5035 config
->radius_authprefer
= type
;
5040 if (!config
->radius_authtypes
)
5042 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5043 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5046 // normalise radius_authtypes_s
5047 if (config
->radius_authprefer
== AUTHPAP
)
5049 strcpy(config
->radius_authtypes_s
, "pap");
5050 if (config
->radius_authtypes
& AUTHCHAP
)
5051 strcat(config
->radius_authtypes_s
, ", chap");
5055 strcpy(config
->radius_authtypes_s
, "chap");
5056 if (config
->radius_authtypes
& AUTHPAP
)
5057 strcat(config
->radius_authtypes_s
, ", pap");
5060 if (!config
->radius_dae_port
)
5061 config
->radius_dae_port
= DAEPORT
;
5063 // re-initialise the random number source
5064 initrandom(config
->random_device
);
5067 for (i
= 0; i
< MAXPLUGINS
; i
++)
5069 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5072 if (*config
->plugins
[i
])
5075 add_plugin(config
->plugins
[i
]);
5077 else if (*config
->old_plugins
[i
])
5080 remove_plugin(config
->old_plugins
[i
]);
5085 guest_accounts_num
= 0;
5086 char *p2
= config
->guest_user
;
5089 char *s
= strpbrk(p2
, " \t,");
5093 while (*s
== ' ' || *s
== '\t')
5100 strcpy(guest_users
[guest_accounts_num
], p2
);
5101 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5102 guest_accounts_num
++;
5105 // Rebuild the guest_user array
5106 strcpy(config
->guest_user
, "");
5108 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5110 strcat(config
->guest_user
, guest_users
[ui
]);
5111 if (ui
<guest_accounts_num
-1)
5113 strcat(config
->guest_user
, ",");
5118 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5119 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5120 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5121 if (!*config
->cluster_interface
)
5122 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5124 if (!config
->cluster_hb_interval
)
5125 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5127 if (!config
->cluster_hb_timeout
)
5128 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5130 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5132 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5133 // late, ensure we're sufficiently larger than that
5134 int t
= 4 * config
->cluster_hb_interval
+ 11;
5136 if (config
->cluster_hb_timeout
< t
)
5138 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5139 config
->cluster_hb_timeout
= t
;
5142 // Push timing changes to the slaves immediately if we're the master
5143 if (config
->cluster_iam_master
)
5144 cluster_heartbeat();
5146 interval
= config
->cluster_hb_interval
;
5147 timeout
= config
->cluster_hb_timeout
;
5151 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5154 if ((f
= fopen(config
->pid_file
, "w")))
5156 fprintf(f
, "%d\n", getpid());
5158 config
->wrote_pid
= 1;
5162 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5167 static void read_config_file()
5171 if (!config
->config_file
) return;
5172 if (!(f
= fopen(config
->config_file
, "r")))
5174 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5178 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5180 LOG(3, 0, 0, "Done reading config file\n");
5184 int sessionsetup(sessionidt s
, tunnelidt t
)
5186 // A session now exists, set it up
5192 CSTAT(sessionsetup
);
5194 LOG(3, s
, t
, "Doing session setup for session\n");
5196 // Join a bundle if the MRRU option is accepted
5197 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5199 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5200 if (join_bundle(s
) > 0)
5201 cluster_send_bundle(session
[s
].bundle
);
5204 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5205 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5212 assign_ip_address(s
);
5215 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5216 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5219 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5220 fmtaddr(htonl(session
[s
].ip
), 0));
5224 // Make sure this is right
5225 session
[s
].tunnel
= t
;
5227 // zap old sessions with same IP and/or username
5228 // Don't kill gardened sessions - doing so leads to a DoS
5229 // from someone who doesn't need to know the password
5232 user
= session
[s
].user
;
5233 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5235 if (i
== s
) continue;
5236 if (!session
[s
].opened
) continue;
5237 // Allow duplicate sessions for multilink ones of the same bundle.
5238 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5240 if (ip
== session
[i
].ip
)
5242 sessionkill(i
, "Duplicate IP address");
5246 if (config
->allow_duplicate_users
) continue;
5247 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5251 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5253 if (!strcasecmp(user
, guest_users
[gu
]))
5259 if (found
) continue;
5261 // Drop the new session in case of duplicate sessionss, not the old one.
5262 if (!strcasecmp(user
, session
[i
].user
))
5263 sessionkill(i
, "Duplicate session for users");
5267 // no need to set a route for the same IP address of the bundle
5268 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5272 // Add the route for this session.
5273 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5275 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5276 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5279 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5282 // Static IPs need to be routed if not already
5283 // convered by a Framed-Route. Anything else is part
5284 // of the IP address pool and is already routed, it
5285 // just needs to be added to the IP cache.
5286 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5287 if (session
[s
].ip_pool_index
== -1) // static ip
5289 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5292 cache_ipmap(session
[s
].ip
, s
);
5295 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5296 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5298 // Run the plugin's against this new session.
5300 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5301 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5304 // Allocate TBFs if throttled
5305 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5306 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5308 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5310 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5311 fmtaddr(htonl(session
[s
].ip
), 0),
5312 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5314 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5316 return 1; // RADIUS OK and IP allocated, done...
5320 // This session just got dropped on us by the master or something.
5321 // Make sure our tables up up to date...
5323 int load_session(sessionidt s
, sessiont
*new)
5329 if (new->ip_pool_index
>= MAXIPPOOL
||
5330 new->tunnel
>= MAXTUNNEL
)
5332 LOG(0, s
, 0, "Strange session update received!\n");
5333 // FIXME! What to do here?
5338 // Ok. All sanity checks passed. Now we're committed to
5339 // loading the new session.
5342 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5344 // See if routes/ip cache need updating
5345 if (new->ip
!= session
[s
].ip
)
5348 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5349 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5350 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5358 // remove old routes...
5359 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5361 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5362 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5365 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5371 if (session
[s
].ip_pool_index
== -1) // static IP
5373 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5375 else // It's part of the IP pool, remove it manually.
5376 uncache_ipmap(session
[s
].ip
);
5381 // add new routes...
5382 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5384 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5385 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5388 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5394 // If there's a new one, add it.
5395 if (new->ip_pool_index
== -1)
5397 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5400 cache_ipmap(new->ip
, s
);
5405 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5406 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5409 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5411 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5415 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5417 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5418 new->filter_out
= 0;
5421 if (new->filter_in
!= session
[s
].filter_in
)
5423 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5424 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5427 if (new->filter_out
!= session
[s
].filter_out
)
5429 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5430 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5433 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5434 // for walking the sessions to forward byte counts to the master.
5435 config
->cluster_highest_sessionid
= s
;
5437 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5439 // Do fixups into address pool.
5440 if (new->ip_pool_index
!= -1)
5441 fix_address_pool(s
);
5446 static void initplugins()
5450 loaded_plugins
= ll_init();
5451 // Initialize the plugins to nothing
5452 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5453 plugins
[i
] = ll_init();
5456 static void *open_plugin(char *plugin_name
, int load
)
5458 char path
[256] = "";
5460 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5461 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5462 return dlopen(path
, RTLD_NOW
);
5465 // plugin callback to get a config value
5466 static void *getconfig(char *key
, enum config_typet type
)
5470 for (i
= 0; config_values
[i
].key
; i
++)
5472 if (!strcmp(config_values
[i
].key
, key
))
5474 if (config_values
[i
].type
== type
)
5475 return ((void *) config
) + config_values
[i
].offset
;
5477 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5478 key
, type
, config_values
[i
].type
);
5484 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5488 static int add_plugin(char *plugin_name
)
5490 static struct pluginfuncs funcs
= {
5495 sessiontbysessionidt
,
5496 sessionidtbysessiont
,
5503 cluster_send_session
,
5506 void *p
= open_plugin(plugin_name
, 1);
5507 int (*initfunc
)(struct pluginfuncs
*);
5512 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5516 if (ll_contains(loaded_plugins
, p
))
5519 return 0; // already loaded
5523 int *v
= dlsym(p
, "plugin_api_version");
5524 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5526 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5532 if ((initfunc
= dlsym(p
, "plugin_init")))
5534 if (!initfunc(&funcs
))
5536 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5542 ll_push(loaded_plugins
, p
);
5544 for (i
= 0; i
< max_plugin_functions
; i
++)
5547 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5549 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5550 ll_push(plugins
[i
], x
);
5554 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5558 static void run_plugin_done(void *plugin
)
5560 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5566 static int remove_plugin(char *plugin_name
)
5568 void *p
= open_plugin(plugin_name
, 0);
5574 if (ll_contains(loaded_plugins
, p
))
5577 for (i
= 0; i
< max_plugin_functions
; i
++)
5580 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5581 ll_delete(plugins
[i
], x
);
5584 ll_delete(loaded_plugins
, p
);
5590 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5594 int run_plugins(int plugin_type
, void *data
)
5596 int (*func
)(void *data
);
5598 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5599 return PLUGIN_RET_ERROR
;
5601 ll_reset(plugins
[plugin_type
]);
5602 while ((func
= ll_next(plugins
[plugin_type
])))
5606 if (r
!= PLUGIN_RET_OK
)
5607 return r
; // stop here
5610 return PLUGIN_RET_OK
;
5613 static void plugins_done()
5617 ll_reset(loaded_plugins
);
5618 while ((p
= ll_next(loaded_plugins
)))
5622 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5624 struct nsctl request
;
5625 struct nsctl response
;
5626 int type
= unpack_control(&request
, buf
, len
);
5630 if (log_stream
&& config
->debug
>= 4)
5634 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5635 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5639 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5640 dump_control(&request
, log_stream
);
5646 case NSCTL_REQ_LOAD
:
5647 if (request
.argc
!= 1)
5649 response
.type
= NSCTL_RES_ERR
;
5651 response
.argv
[0] = "name of plugin required";
5653 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5655 response
.type
= NSCTL_RES_ERR
;
5657 response
.argv
[0] = !r
5658 ? "plugin already loaded"
5659 : "error loading plugin";
5663 response
.type
= NSCTL_RES_OK
;
5669 case NSCTL_REQ_UNLOAD
:
5670 if (request
.argc
!= 1)
5672 response
.type
= NSCTL_RES_ERR
;
5674 response
.argv
[0] = "name of plugin required";
5676 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5678 response
.type
= NSCTL_RES_ERR
;
5680 response
.argv
[0] = !r
5681 ? "plugin not loaded"
5682 : "plugin not found";
5686 response
.type
= NSCTL_RES_OK
;
5692 case NSCTL_REQ_HELP
:
5693 response
.type
= NSCTL_RES_OK
;
5696 ll_reset(loaded_plugins
);
5697 while ((p
= ll_next(loaded_plugins
)))
5699 char **help
= dlsym(p
, "plugin_control_help");
5700 while (response
.argc
< 0xff && help
&& *help
)
5701 response
.argv
[response
.argc
++] = *help
++;
5706 case NSCTL_REQ_CONTROL
:
5708 struct param_control param
= {
5709 config
->cluster_iam_master
,
5716 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5718 if (r
== PLUGIN_RET_ERROR
)
5720 response
.type
= NSCTL_RES_ERR
;
5722 response
.argv
[0] = param
.additional
5724 : "error returned by plugin";
5726 else if (r
== PLUGIN_RET_NOTMASTER
)
5728 static char msg
[] = "must be run on master: 000.000.000.000";
5730 response
.type
= NSCTL_RES_ERR
;
5732 if (config
->cluster_master_address
)
5734 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5735 response
.argv
[0] = msg
;
5739 response
.argv
[0] = "must be run on master: none elected";
5742 else if (!(param
.response
& NSCTL_RESPONSE
))
5744 response
.type
= NSCTL_RES_ERR
;
5746 response
.argv
[0] = param
.response
5747 ? "unrecognised response value from plugin"
5748 : "unhandled action";
5752 response
.type
= param
.response
;
5754 if (param
.additional
)
5757 response
.argv
[0] = param
.additional
;
5765 response
.type
= NSCTL_RES_ERR
;
5767 response
.argv
[0] = "error unpacking control packet";
5770 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5773 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5777 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5780 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5781 if (log_stream
&& config
->debug
>= 4)
5783 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5784 dump_control(&response
, log_stream
);
5788 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5789 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5794 static tunnelidt
new_tunnel()
5797 for (i
= 1; i
< MAXTUNNEL
; i
++)
5799 if (tunnel
[i
].state
== TUNNELFREE
)
5801 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5802 if (i
> config
->cluster_highest_tunnelid
)
5803 config
->cluster_highest_tunnelid
= i
;
5807 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5812 // We're becoming the master. Do any required setup..
5814 // This is principally telling all the plugins that we're
5815 // now a master, and telling them about all the sessions
5816 // that are active too..
5818 void become_master(void)
5821 static struct event_data d
[RADIUS_FDS
];
5822 struct epoll_event e
;
5824 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5826 // running a bunch of iptables commands is slow and can cause
5827 // the master to drop tunnels on takeover--kludge around the
5828 // problem by forking for the moment (note: race)
5829 if (!fork_and_close())
5831 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5833 if (!session
[s
].opened
) // Not an in-use session.
5836 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5843 for (i
= 0; i
< RADIUS_FDS
; i
++)
5845 d
[i
].type
= FD_TYPE_RADIUS
;
5849 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5853 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5859 if (CLI_HELP_REQUESTED
)
5860 return CLI_HELP_NO_ARGS
;
5863 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5865 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5868 if (!session
[s
].opened
)
5871 idle
= time_now
- session
[s
].last_data
;
5872 idle
/= 5 ; // In multiples of 5 seconds.
5882 for (i
= 0; i
< 63; ++i
)
5884 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5886 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5887 cli_print(cli
, "%d total sessions open.", count
);
5891 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5897 if (CLI_HELP_REQUESTED
)
5898 return CLI_HELP_NO_ARGS
;
5901 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5903 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5906 if (!session
[s
].opened
)
5909 d
= time_now
- session
[s
].opened
;
5912 while (d
> 1 && open
< 32)
5922 for (i
= 0; i
< 30; ++i
)
5924 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5927 cli_print(cli
, "%d total sessions open.", count
);
5933 * This unencodes the AVP using the L2TP secret and the previously
5934 * stored random vector. It overwrites the hidden data with the
5935 * unhidden AVP subformat.
5937 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5943 uint16_t m
= htons(type
);
5945 // Compute initial pad
5947 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5948 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5949 MD5_Update(&ctx
, vector
, vec_len
);
5950 MD5_Final(digest
, &ctx
);
5952 // pointer to last decoded 16 octets
5957 // calculate a new pad based on the last decoded block
5958 if (d
>= sizeof(digest
))
5961 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5962 MD5_Update(&ctx
, last
, sizeof(digest
));
5963 MD5_Final(digest
, &ctx
);
5969 *value
++ ^= digest
[d
++];
5974 int find_filter(char const *name
, size_t len
)
5979 for (i
= 0; i
< MAXFILTER
; i
++)
5981 if (!*ip_filters
[i
].name
)
5989 if (strlen(ip_filters
[i
].name
) != len
)
5992 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5999 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6003 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6004 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6005 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6006 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6007 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6013 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6017 case FILTER_FLAG_OP_ANY
:
6018 return (flags
& sflags
) || (~flags
& cflags
);
6020 case FILTER_FLAG_OP_ALL
:
6021 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6023 case FILTER_FLAG_OP_EST
:
6024 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6030 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6032 uint16_t frag_offset
;
6036 uint16_t src_port
= 0;
6037 uint16_t dst_port
= 0;
6039 ip_filter_rulet
*rule
;
6041 if (len
< 20) // up to end of destination address
6044 if ((*buf
>> 4) != 4) // IPv4
6047 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6049 src_ip
= *(in_addr_t
*) (buf
+ 12);
6050 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6052 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6054 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6055 if (len
< l
+ 4) // ports
6058 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6059 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6060 if (proto
== IPPROTO_TCP
)
6062 if (len
< l
+ 14) // flags
6065 flags
= buf
[l
+ 13] & 0x3f;
6069 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6071 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6074 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6075 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6078 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6079 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6084 // layer 4 deny rules are skipped
6085 if (rule
->action
== FILTER_ACTION_DENY
&&
6086 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6094 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6096 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6099 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6102 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6103 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6110 return rule
->action
== FILTER_ACTION_PERMIT
;