3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
7 char const *cvs_id_l2tpns
= "$Id: l2tpns.c,v 1.176 2011/01/20 12:48:40 bodea Exp $";
13 #include <linux/if_tun.h>
17 #include <net/route.h>
20 #include <netinet/in.h>
21 #include <netinet/ip6.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
31 #include <sys/resource.h>
39 #include <sys/sysinfo.h>
41 #include <linux/netlink.h>
42 #include <linux/rtnetlink.h>
49 #include "constants.h"
59 configt
*config
= NULL
; // all configuration
60 int nlfd
= -1; // netlink socket
61 int tunfd
= -1; // tun interface file handle. (network device)
62 int udpfd
= -1; // UDP file handle
63 int controlfd
= -1; // Control signal handle
64 int clifd
= -1; // Socket listening for CLI connections.
65 int daefd
= -1; // Socket listening for DAE connections.
66 int snoopfd
= -1; // UDP file handle for sending out intercept data
67 int *radfds
= NULL
; // RADIUS requests file handles
68 int rand_fd
= -1; // Random data source
69 int cluster_sockfd
= -1; // Intra-cluster communications socket.
70 int epollfd
= -1; // event polling
71 time_t basetime
= 0; // base clock
72 char hostname
[MAXHOSTNAME
] = ""; // us.
73 static int tunidx
; // ifr_ifindex of tun device
74 int nlseqnum
= 0; // netlink sequence number
75 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
76 static int syslog_log
= 0; // are we logging to syslog
77 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
78 uint32_t last_id
= 0; // Unique ID for radius accounting
80 char guest_users
[10][32]; // Array of guest users
81 int guest_accounts_num
= 0; // Number of guest users
83 // calculated from config->l2tp_mtu
84 uint16_t MRU
= 0; // PPP MRU
85 uint16_t MSS
= 0; // TCP MSS
87 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
88 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
93 } ip_hash
[256]; // Mapping from IP address to session structures.
97 struct ipv6radix
*branch
;
98 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
101 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
102 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
105 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
106 time_t time_now
= 0; // Current time in seconds since epoch.
107 static char time_now_string
[64] = {0}; // Current time as a string.
108 static int time_changed
= 0; // time_now changed
109 char main_quit
= 0; // True if we're in the process of exiting.
110 static char main_reload
= 0; // Re-load pending
111 linked_list
*loaded_plugins
;
112 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
114 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
115 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
117 config_descriptt config_values
[] = {
118 CONFIG("debug", debug
, INT
),
119 CONFIG("log_file", log_filename
, STRING
),
120 CONFIG("pid_file", pid_file
, STRING
),
121 CONFIG("random_device", random_device
, STRING
),
122 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
123 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
124 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
125 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
126 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
127 CONFIG("primary_dns", default_dns1
, IPv4
),
128 CONFIG("secondary_dns", default_dns2
, IPv4
),
129 CONFIG("primary_radius", radiusserver
[0], IPv4
),
130 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
131 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
132 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
133 CONFIG("radius_accounting", radius_accounting
, BOOL
),
134 CONFIG("radius_interim", radius_interim
, INT
),
135 CONFIG("radius_secret", radiussecret
, STRING
),
136 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
137 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
138 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
139 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
140 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
141 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
142 CONFIG("guest_account", guest_user
, STRING
),
143 CONFIG("bind_address", bind_address
, IPv4
),
144 CONFIG("peer_address", peer_address
, IPv4
),
145 CONFIG("send_garp", send_garp
, BOOL
),
146 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
147 CONFIG("throttle_buckets", num_tbfs
, INT
),
148 CONFIG("accounting_dir", accounting_dir
, STRING
),
149 CONFIG("dump_speed", dump_speed
, BOOL
),
150 CONFIG("multi_read_count", multi_read_count
, INT
),
151 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
152 CONFIG("lock_pages", lock_pages
, BOOL
),
153 CONFIG("icmp_rate", icmp_rate
, INT
),
154 CONFIG("packet_limit", max_packets
, INT
),
155 CONFIG("cluster_address", cluster_address
, IPv4
),
156 CONFIG("cluster_interface", cluster_interface
, STRING
),
157 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
158 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
159 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
160 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
161 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
162 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
163 CONFIG("hostname", hostname
, STRING
),
164 CONFIG("nexthop_address", nexthop_address
, IPv4
),
165 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
169 static char *plugin_functions
[] = {
174 "plugin_new_session",
175 "plugin_kill_session",
177 "plugin_radius_response",
178 "plugin_radius_reset",
179 "plugin_radius_account",
180 "plugin_become_master",
181 "plugin_new_session_master",
184 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
186 // Counters for shutdown sessions
187 static sessiont shut_acct
[8192];
188 static sessionidt shut_acct_n
= 0;
190 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
191 bundlet
*bundle
= NULL
; // Array of bundle structures.
192 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
193 sessiont
*session
= NULL
; // Array of session structures.
194 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
195 radiust
*radius
= NULL
; // Array of radius structures.
196 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
197 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
198 static controlt
*controlfree
= 0;
199 struct Tstats
*_statistics
= NULL
;
201 struct Tringbuffer
*ringbuffer
= NULL
;
204 static ssize_t
netlink_send(struct nlmsghdr
*nh
);
205 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
);
206 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
207 static void uncache_ipmap(in_addr_t ip
);
208 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
209 static void free_ip_address(sessionidt s
);
210 static void dump_acct_info(int all
);
211 static void sighup_handler(int sig
);
212 static void shutdown_handler(int sig
);
213 static void sigchild_handler(int sig
);
214 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
215 static void update_config(void);
216 static void read_config_file(void);
217 static void initplugins(void);
218 static int add_plugin(char *plugin_name
);
219 static int remove_plugin(char *plugin_name
);
220 static void plugins_done(void);
221 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
222 static tunnelidt
new_tunnel(void);
223 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
224 static void bundleclear(bundleidt b
);
226 // on slaves, alow BGP to withdraw cleanly before exiting
229 // quit actions (master)
230 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
231 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
233 // return internal time (10ths since process startup), set f if given
234 // as a side-effect sets time_now, and time_changed
235 static clockt
now(double *f
)
239 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
240 if (t
.tv_sec
!= time_now
)
245 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
248 // work out a retry time based on try number
249 // This is a straight bounded exponential backoff.
250 // Maximum re-try time is 32 seconds. (2^5).
251 clockt
backoff(uint8_t try)
253 if (try > 5) try = 5; // max backoff
254 return now(NULL
) + 10 * (1 << try);
259 // Log a debug message. Typically called via the LOG macro
261 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
263 static char message
[65536] = {0};
269 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
270 ringbuffer
->tail
= 0;
271 if (ringbuffer
->tail
== ringbuffer
->head
)
272 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
273 ringbuffer
->head
= 0;
275 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
276 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
277 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
278 va_start(ap
, format
);
279 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
284 if (config
->debug
< level
) return;
286 va_start(ap
, format
);
287 vsnprintf(message
, sizeof(message
), format
, ap
);
290 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
292 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
297 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
300 const uint8_t *d
= data
;
302 if (config
->debug
< level
) return;
304 // No support for _log_hex to syslog
307 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
308 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
310 for (i
= 0; i
< maxsize
; )
312 fprintf(log_stream
, "%4X: ", i
);
313 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
315 fprintf(log_stream
, "%02X ", d
[j
]);
317 fputs(": ", log_stream
);
320 for (; j
< i
+ 16; j
++)
322 fputs(" ", log_stream
);
324 fputs(": ", log_stream
);
327 fputs(" ", log_stream
);
328 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
330 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
331 fputc(d
[j
], log_stream
);
333 fputc('.', log_stream
);
336 fputs(" ", log_stream
);
340 fputs("\n", log_stream
);
344 setbuf(log_stream
, NULL
);
348 // update a counter, accumulating 2^32 wraps
349 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
351 uint32_t new = *counter
+ delta
;
358 // initialise the random generator
359 static void initrandom(char *source
)
361 static char path
[sizeof(config
->random_device
)] = "*undefined*";
363 // reinitialise only if we are forced to do so or if the config has changed
364 if (source
&& !strncmp(path
, source
, sizeof(path
)))
367 // close previous source, if any
376 snprintf(path
, sizeof(path
), "%s", source
);
380 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
382 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
383 path
, strerror(errno
));
388 // fill buffer with random data
389 void random_data(uint8_t *buf
, int len
)
396 n
= read(rand_fd
, buf
, len
);
397 if (n
>= len
) return;
402 LOG(0, 0, 0, "Error reading from random source: %s\n",
405 // fall back to rand()
413 // append missing data
415 // not using the low order bits from the prng stream
416 buf
[n
++] = (rand() >> 4) & 0xff;
421 // This adds it to the routing table, advertises it
422 // via BGP if enabled, and stuffs it into the
423 // 'sessionbyip' cache.
425 // 'ip' must be in _host_ order.
427 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
437 if (!prefixlen
) prefixlen
= 32;
439 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
441 memset(&req
, 0, sizeof(req
));
445 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
446 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
449 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
450 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
452 req
.rt
.rtm_family
= AF_INET
;
453 req
.rt
.rtm_dst_len
= prefixlen
;
454 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
455 req
.rt
.rtm_protocol
= RTPROT_BOOT
; // XXX
456 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
457 req
.rt
.rtm_type
= RTN_UNICAST
;
459 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
461 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
465 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
468 LOG(1, s
, 0, "Route %s %s/%d%s%s\n", add
? "add" : "del",
469 fmtaddr(htonl(ip
), 0), prefixlen
,
470 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
472 if (netlink_send(&req
.nh
) < 0)
473 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
477 bgp_add_route(htonl(ip
), prefixlen
);
479 bgp_del_route(htonl(ip
), prefixlen
);
482 // Add/Remove the IPs to the 'sessionbyip' cache.
483 // Note that we add the zero address in the case of
484 // a network route. Roll on CIDR.
486 // Note that 's == 0' implies this is the address pool.
487 // We still cache it here, because it will pre-fill
488 // the malloc'ed tree.
492 if (!add
) // Are we deleting a route?
493 s
= 0; // Caching the session as '0' is the same as uncaching.
495 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
500 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
508 char ipv6addr
[INET6_ADDRSTRLEN
];
510 if (!config
->ipv6_prefix
.s6_addr
[0])
512 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
516 memset(&req
, 0, sizeof(req
));
520 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
521 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
524 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
525 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
527 req
.rt
.rtm_family
= AF_INET6
;
528 req
.rt
.rtm_dst_len
= prefixlen
;
529 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
530 req
.rt
.rtm_protocol
= RTPROT_BOOT
; // XXX
531 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
532 req
.rt
.rtm_type
= RTN_UNICAST
;
534 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
535 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
537 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
539 LOG(1, 0, 0, "Route %s %s/%d\n",
541 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
544 if (netlink_send(&req
.nh
) < 0)
545 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
549 bgp_add_route6(ip
, prefixlen
);
551 bgp_del_route6(ip
, prefixlen
);
556 if (!add
) // Are we deleting a route?
557 s
= 0; // Caching the session as '0' is the same as uncaching.
559 cache_ipv6map(ip
, prefixlen
, s
);
566 // Set up netlink socket
567 static void initnetlink(void)
569 struct sockaddr_nl nladdr
;
571 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
574 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
578 memset(&nladdr
, 0, sizeof(nladdr
));
579 nladdr
.nl_family
= AF_NETLINK
;
580 nladdr
.nl_pid
= getpid();
582 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
584 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
589 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
591 struct sockaddr_nl nladdr
;
595 nh
->nlmsg_pid
= getpid();
596 nh
->nlmsg_seq
= ++nlseqnum
;
598 // set kernel address
599 memset(&nladdr
, 0, sizeof(nladdr
));
600 nladdr
.nl_family
= AF_NETLINK
;
602 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
603 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
605 return sendmsg(nlfd
, &msg
, 0);
608 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
610 struct sockaddr_nl nladdr
;
614 // set kernel address
615 memset(&nladdr
, 0, sizeof(nladdr
));
616 nladdr
.nl_family
= AF_NETLINK
;
618 iov
= (struct iovec
){ buf
, len
};
619 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
621 return recvmsg(nlfd
, &msg
, 0);
624 /* adapted from iproute2 */
625 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
627 int len
= RTA_LENGTH(alen
);
630 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
631 rta
->rta_type
= type
;
633 memcpy(RTA_DATA(rta
), data
, alen
);
634 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
637 // messages corresponding to different phases seq number
638 static char *tun_nl_phase_msg
[] = {
640 "getting tun interface index",
641 "setting tun interface parameters",
642 "setting tun IPv4 address",
643 "setting tun LL IPv6 address",
644 "setting tun global IPv6 address",
648 // Set up TUN interface
649 static void inittun(void)
651 struct ifinfomsg ifinfo
;
654 memset(&ifr
, 0, sizeof(ifr
));
655 ifr
.ifr_flags
= IFF_TUN
;
657 tunfd
= open(TUNDEVICE
, O_RDWR
);
660 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
664 int flags
= fcntl(tunfd
, F_GETFL
, 0);
665 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
667 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
669 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
672 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
) - 1);
673 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
));
676 // get the interface index
679 struct ifinfomsg ifinfo
;
683 struct nlmsghdr
*resp_nh
;
685 req
.nh
.nlmsg_type
= RTM_GETLINK
;
686 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
687 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifinfo
));
689 req
.ifinfo
.ifi_family
= AF_UNSPEC
; // as the man says
691 netlink_addattr(&req
.nh
, IFLA_IFNAME
, config
->tundevice
, strlen(config
->tundevice
)+1);
693 if(netlink_send(&req
.nh
) < 0 || (len
= netlink_recv(buf
, sizeof(buf
))) < 0)
695 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno
));
699 resp_nh
= (struct nlmsghdr
*)buf
;
700 if (!NLMSG_OK (resp_nh
, len
))
702 LOG(0, 0, 0, "Malformed answer getting tun ifindex %ld\n", len
);
706 memcpy(&ifinfo
, NLMSG_DATA(resp_nh
), sizeof(ifinfo
));
708 tunidx
= ifinfo
.ifi_index
;
715 struct ifinfomsg ifinfo
;
716 struct ifaddrmsg ifaddr
;
718 char rtdata
[32]; // 32 should be enough
720 uint32_t txqlen
, mtu
;
723 memset(&req
, 0, sizeof(req
));
725 req
.nh
.nlmsg_type
= RTM_SETLINK
;
726 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
727 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
729 req
.ifmsg
.ifinfo
= ifinfo
;
730 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
731 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
733 /* Bump up the qlen to deal with bursts from the network */
735 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
736 /* set MTU to modem MRU */
738 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
740 if (netlink_send(&req
.nh
) < 0)
743 memset(&req
, 0, sizeof(req
));
745 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
746 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
747 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
749 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
750 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
751 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
752 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
754 if (config
->bind_address
)
755 ip
= config
->bind_address
;
757 ip
= 0x01010101; // 1.1.1.1
758 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
760 if (netlink_send(&req
.nh
) < 0)
763 // Only setup IPv6 on the tun device if we have a configured prefix
764 if (config
->ipv6_prefix
.s6_addr
[0]) {
767 memset(&req
, 0, sizeof(req
));
769 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
770 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
771 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
773 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
774 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
775 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
776 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
778 // Link local address is FE80::1
779 memset(&ip6
, 0, sizeof(ip6
));
780 ip6
.s6_addr
[0] = 0xFE;
781 ip6
.s6_addr
[1] = 0x80;
783 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
785 if (netlink_send(&req
.nh
) < 0)
788 memset(&req
, 0, sizeof(req
));
790 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
791 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
792 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
794 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
795 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
796 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
797 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
799 // Global address is prefix::1
800 ip6
= config
->ipv6_prefix
;
802 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
804 if (netlink_send(&req
.nh
) < 0)
808 memset(&req
, 0, sizeof(req
));
810 req
.nh
.nlmsg_type
= NLMSG_DONE
;
811 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
813 if (netlink_send(&req
.nh
) < 0)
816 // if we get an error for seqnum < min_initok_nlseqnum,
817 // we must exit as initialization went wrong
818 if (config
->ipv6_prefix
.s6_addr
[0])
819 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
821 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
827 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
832 static void initudp(void)
835 struct sockaddr_in addr
;
838 memset(&addr
, 0, sizeof(addr
));
839 addr
.sin_family
= AF_INET
;
840 addr
.sin_port
= htons(L2TPPORT
);
841 addr
.sin_addr
.s_addr
= config
->bind_address
;
842 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
843 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
845 int flags
= fcntl(udpfd
, F_GETFL
, 0);
846 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
848 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
850 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
855 memset(&addr
, 0, sizeof(addr
));
856 addr
.sin_family
= AF_INET
;
857 addr
.sin_port
= htons(NSCTL_PORT
);
858 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
859 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
860 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
861 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
863 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
867 // Dynamic Authorization Extensions to RADIUS
868 memset(&addr
, 0, sizeof(addr
));
869 addr
.sin_family
= AF_INET
;
870 addr
.sin_port
= htons(config
->radius_dae_port
);
871 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
872 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
873 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
874 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
876 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
881 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
885 // Find session by IP, < 1 for not found
887 // Confusingly enough, this 'ip' must be
888 // in _network_ order. This being the common
889 // case when looking it up from IP packet headers.
891 // We actually use this cache for two things.
892 // #1. For used IP addresses, this maps to the
893 // session ID that it's used by.
894 // #2. For un-used IP addresses, this maps to the
895 // index into the pool table that contains that
899 static sessionidt
lookup_ipmap(in_addr_t ip
)
901 uint8_t *a
= (uint8_t *) &ip
;
902 union iphash
*h
= ip_hash
;
904 if (!(h
= h
[*a
++].idx
)) return 0;
905 if (!(h
= h
[*a
++].idx
)) return 0;
906 if (!(h
= h
[*a
++].idx
)) return 0;
911 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
913 struct ipv6radix
*curnode
;
916 char ipv6addr
[INET6_ADDRSTRLEN
];
918 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
922 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
924 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
929 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
930 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
937 sessionidt
sessionbyip(in_addr_t ip
)
939 sessionidt s
= lookup_ipmap(ip
);
942 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
948 sessionidt
sessionbyipv6(struct in6_addr ip
)
951 CSTAT(sessionbyipv6
);
953 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
954 (ip
.s6_addr
[0] == 0xFE &&
955 ip
.s6_addr
[1] == 0x80 &&
956 ip
.s6_addr16
[1] == 0 &&
957 ip
.s6_addr16
[2] == 0 &&
958 ip
.s6_addr16
[3] == 0)) {
959 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
961 s
= lookup_ipv6map(ip
);
964 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
971 // Take an IP address in HOST byte order and
972 // add it to the sessionid by IP cache.
974 // (It's actually cached in network order)
976 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
978 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
979 uint8_t *a
= (uint8_t *) &nip
;
980 union iphash
*h
= ip_hash
;
983 for (i
= 0; i
< 3; i
++)
985 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
994 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
997 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
998 // else a map to an ip pool index.
1001 static void uncache_ipmap(in_addr_t ip
)
1003 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1006 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1010 struct ipv6radix
*curnode
;
1011 char ipv6addr
[INET6_ADDRSTRLEN
];
1013 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
1015 bytes
= prefixlen
>> 3;
1018 if (curnode
->branch
== NULL
)
1020 if (!(curnode
->branch
= calloc(256,
1021 sizeof (struct ipv6radix
))))
1024 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1031 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1032 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1036 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1037 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1043 // CLI list to dump current ipcache.
1045 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1047 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1051 if (CLI_HELP_REQUESTED
)
1052 return CLI_HELP_NO_ARGS
;
1054 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1056 for (i
= 0; i
< 256; ++i
)
1062 for (j
= 0; j
< 256; ++j
)
1068 for (k
= 0; k
< 256; ++k
)
1074 for (l
= 0; l
< 256; ++l
)
1079 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1085 cli_print(cli
, "%d entries in cache", count
);
1090 // Find session by username, 0 for not found
1091 // walled garden users aren't authenticated, so the username is
1092 // reasonably useless. Ignore them to avoid incorrect actions
1094 // This is VERY inefficent. Don't call it often. :)
1096 sessionidt
sessionbyuser(char *username
)
1099 CSTAT(sessionbyuser
);
1101 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1103 if (!session
[s
].opened
)
1106 if (session
[s
].walled_garden
)
1107 continue; // Skip walled garden users.
1109 if (!strncmp(session
[s
].user
, username
, 128))
1113 return 0; // Not found.
1116 void send_garp(in_addr_t ip
)
1122 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1125 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1128 memset(&ifr
, 0, sizeof(ifr
));
1129 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1130 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1132 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1136 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1137 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1139 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1144 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1147 static sessiont
*sessiontbysessionidt(sessionidt s
)
1149 if (!s
|| s
>= MAXSESSION
) return NULL
;
1153 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1155 sessionidt val
= s
-session
;
1156 if (s
< session
|| val
>= MAXSESSION
) return 0;
1160 // actually send a control message for a specific tunnel
1161 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1163 struct sockaddr_in addr
;
1169 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1170 STAT(tunnel_tx_errors
);
1176 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1177 STAT(tunnel_tx_errors
);
1181 memset(&addr
, 0, sizeof(addr
));
1182 addr
.sin_family
= AF_INET
;
1183 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1184 addr
.sin_port
= htons(tunnel
[t
].port
);
1186 // sequence expected, if sequence in message
1187 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1189 // If this is a control message, deal with retries
1192 tunnel
[t
].last
= time_now
; // control message sent
1193 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1196 STAT(tunnel_retries
);
1197 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1201 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1203 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1204 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1205 STAT(tunnel_tx_errors
);
1209 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1210 STAT(tunnel_tx_packets
);
1211 INC_STAT(tunnel_tx_bytes
, l
);
1215 // Tiny helper function to write data to
1216 // the 'tun' device.
1218 int tun_write(uint8_t * data
, int size
)
1220 return write(tunfd
, data
, size
);
1223 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1224 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1226 int d
= (tcp
[12] >> 4) * 4;
1233 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1236 if (tcp
+ d
> buf
+ len
) // short?
1244 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1247 if (mss
+ 2 > data
) return; // short?
1251 if (*opts
== 0) return; // end of options
1252 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1255 opts
+= opts
[1]; // skip over option
1258 if (!mss
) return; // not found
1259 orig
= ntohs(*(uint16_t *) mss
);
1261 if (orig
<= MSS
) return; // mss OK
1263 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1264 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1265 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1266 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1269 *(int16_t *) mss
= htons(MSS
);
1271 // adjust checksum (see rfc1141)
1272 sum
= orig
+ (~MSS
& 0xffff);
1273 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1274 sum
= (sum
& 0xffff) + (sum
>> 16);
1275 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1278 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1282 // Skip the four extra bytes
1294 proto
= ntohs(*(uint16_t *) p
);
1302 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1303 return; // closing session, PPP not processed
1305 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1306 processipin(s
, t
, p
, l
);
1308 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1312 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1313 return; // closing session, PPP not processed
1316 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1317 processipv6in(s
, t
, p
, l
);
1319 else if (proto
== PPPIPCP
)
1321 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1322 processipcp(s
, t
, p
, l
);
1324 else if (proto
== PPPCCP
)
1326 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1327 processccp(s
, t
, p
, l
);
1331 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1335 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1337 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1338 sp
->cout_delta
+= len
;
1340 sp
->last_data
= time_now
;
1342 sess_local
[s
].cout
+= len
; // To send to master..
1343 sess_local
[s
].pout
++;
1346 // process outgoing (to tunnel) IP
1348 static void processipout(uint8_t *buf
, int len
)
1355 uint8_t *data
= buf
; // Keep a copy of the originals.
1358 uint8_t fragbuf
[MAXETHER
+ 20];
1360 CSTAT(processipout
);
1362 if (len
< MIN_IP_SIZE
)
1364 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1365 STAT(tun_rx_errors
);
1368 if (len
>= MAXETHER
)
1370 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1371 STAT(tun_rx_errors
);
1375 // Skip the tun header
1379 // Got an IP header now
1380 if (*(uint8_t *)(buf
) >> 4 != 4)
1382 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1386 ip
= *(uint32_t *)(buf
+ 16);
1387 if (!(s
= sessionbyip(ip
)))
1389 // Is this a packet for a session that doesn't exist?
1390 static int rate
= 0; // Number of ICMP packets we've sent this second.
1391 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1393 if (last
!= time_now
)
1399 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1401 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1402 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1403 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1408 t
= session
[s
].tunnel
;
1409 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1411 LOG(3, s
, t
, "Packet size more than session MRU\n");
1417 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1418 if (config
->max_packets
> 0)
1420 if (sess_local
[s
].last_packet_out
== TIME
)
1422 int max
= config
->max_packets
;
1424 // All packets for throttled sessions are handled by the
1425 // master, so further limit by using the throttle rate.
1426 // A bit of a kludge, since throttle rate is in kbps,
1427 // but should still be generous given our average DSL
1428 // packet size is 200 bytes: a limit of 28kbps equates
1429 // to around 180 packets per second.
1430 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1431 max
= sp
->throttle_out
;
1433 if (++sess_local
[s
].packets_out
> max
)
1435 sess_local
[s
].packets_dropped
++;
1441 if (sess_local
[s
].packets_dropped
)
1443 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1444 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1445 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1446 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1450 sess_local
[s
].last_packet_out
= TIME
;
1451 sess_local
[s
].packets_out
= 1;
1452 sess_local
[s
].packets_dropped
= 0;
1456 // run access-list if any
1457 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1460 // adjust MSS on SYN and SYN,ACK packets with options
1461 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1463 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1464 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1465 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1470 // Are we throttling this session?
1471 if (config
->cluster_iam_master
)
1472 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1474 master_throttle_packet(sp
->tbf_out
, data
, size
);
1478 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1480 // We are walled-gardening this
1481 master_garden_packet(s
, data
, size
);
1485 // Add on L2TP header
1488 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1490 bid
= session
[s
].bundle
;
1491 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1492 t
= session
[s
].tunnel
;
1494 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1495 if(len
> MINFRAGLEN
)
1497 // Partition the packet to "bundle[b].num_of_links" fragments
1498 bundlet
*b
= &bundle
[bid
];
1499 uint32_t num_of_links
= b
->num_of_links
;
1500 uint32_t fraglen
= len
/ num_of_links
;
1501 fraglen
= (fraglen
> session
[s
].mru
? session
[s
].mru
: fraglen
);
1502 uint32_t last_fraglen
= fraglen
+ len
% num_of_links
;
1503 last_fraglen
= (last_fraglen
> session
[s
].mru
? len
% num_of_links
: last_fraglen
);
1504 uint32_t remain
= len
;
1506 // send the first packet
1507 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1509 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1511 update_session_out_stat(s
, sp
, fraglen
);
1513 while (remain
> last_fraglen
)
1515 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1516 t
= session
[s
].tunnel
;
1518 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1519 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1521 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1522 update_session_out_stat(s
, sp
, fraglen
);
1525 // send the last fragment
1526 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1527 t
= session
[s
].tunnel
;
1529 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1530 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1532 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1533 update_session_out_stat(s
, sp
, remain
);
1534 if (remain
!= last_fraglen
)
1535 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1538 // Send it as one frame
1539 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1541 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1542 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1543 update_session_out_stat(s
, sp
, len
);
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
);
1555 // Snooping this session, send it to intercept box
1556 if (sp
->snoop_ip
&& sp
->snoop_port
)
1557 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1562 // process outgoing (to tunnel) IPv6
1564 static void processipv6out(uint8_t * buf
, int len
)
1570 struct in6_addr ip6
;
1572 uint8_t *data
= buf
; // Keep a copy of the originals.
1575 uint8_t b
[MAXETHER
+ 20];
1577 CSTAT(processipv6out
);
1579 if (len
< MIN_IP_SIZE
)
1581 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1582 STAT(tunnel_tx_errors
);
1585 if (len
>= MAXETHER
)
1587 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1588 STAT(tunnel_tx_errors
);
1592 // Skip the tun header
1596 // Got an IP header now
1597 if (*(uint8_t *)(buf
) >> 4 != 6)
1599 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1603 ip6
= *(struct in6_addr
*)(buf
+24);
1604 s
= sessionbyipv6(ip6
);
1608 ip
= *(uint32_t *)(buf
+ 32);
1609 s
= sessionbyip(ip
);
1614 // Is this a packet for a session that doesn't exist?
1615 static int rate
= 0; // Number of ICMP packets we've sent this second.
1616 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1618 if (last
!= time_now
)
1624 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1626 // FIXME: Should send icmp6 host unreachable
1630 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1632 bundleidt bid
= session
[s
].bundle
;
1633 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1634 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1636 t
= session
[s
].tunnel
;
1638 sp
->last_data
= time_now
;
1640 // FIXME: add DoS prevention/filters?
1644 // Are we throttling this session?
1645 if (config
->cluster_iam_master
)
1646 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1648 master_throttle_packet(sp
->tbf_out
, data
, size
);
1651 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1653 // We are walled-gardening this
1654 master_garden_packet(s
, data
, size
);
1658 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1660 // Add on L2TP header
1662 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1664 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1667 // Snooping this session, send it to intercept box
1668 if (sp
->snoop_ip
&& sp
->snoop_port
)
1669 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1671 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1672 sp
->cout_delta
+= len
;
1676 sess_local
[s
].cout
+= len
; // To send to master..
1677 sess_local
[s
].pout
++;
1681 // Helper routine for the TBF filters.
1682 // Used to send queued data in to the user!
1684 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1690 uint8_t b
[MAXETHER
+ 20];
1692 if (len
< 0 || len
> MAXETHER
)
1694 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1698 // Skip the tun header
1702 ip
= *(in_addr_t
*)(buf
+ 16);
1707 t
= session
[s
].tunnel
;
1710 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1712 // Add on L2TP header
1714 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1716 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1719 // Snooping this session.
1720 if (sp
->snoop_ip
&& sp
->snoop_port
)
1721 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1723 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1724 sp
->cout_delta
+= len
;
1728 sess_local
[s
].cout
+= len
; // To send to master..
1729 sess_local
[s
].pout
++;
1732 // add an AVP (16 bit)
1733 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1735 uint16_t l
= (m
? 0x8008 : 0x0008);
1736 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1737 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1738 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1739 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1743 // add an AVP (32 bit)
1744 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1746 uint16_t l
= (m
? 0x800A : 0x000A);
1747 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1748 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1749 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1750 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1754 // add an AVP (string)
1755 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1757 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1758 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1759 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1760 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1761 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1762 c
->length
+= 6 + strlen(val
);
1766 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1768 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1769 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1770 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1771 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1772 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1773 c
->length
+= 6 + len
;
1776 // new control connection
1777 static controlt
*controlnew(uint16_t mtype
)
1781 c
= malloc(sizeof(controlt
));
1785 controlfree
= c
->next
;
1789 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1791 control16(c
, 0, mtype
, 1);
1795 // send zero block if nothing is waiting
1797 static void controlnull(tunnelidt t
)
1800 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1803 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1804 *(uint16_t *) (buf
+ 2) = htons(12); // length
1805 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1806 *(uint16_t *) (buf
+ 6) = htons(0); // session
1807 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1808 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1809 tunnelsend(buf
, 12, t
);
1812 // add a control message to a tunnel, and send if within window
1813 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1815 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1816 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1817 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1818 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1819 tunnel
[t
].ns
++; // advance sequence
1820 // link in message in to queue
1821 if (tunnel
[t
].controlc
)
1822 tunnel
[t
].controle
->next
= c
;
1824 tunnel
[t
].controls
= c
;
1826 tunnel
[t
].controle
= c
;
1827 tunnel
[t
].controlc
++;
1829 // send now if space in window
1830 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1832 tunnel
[t
].try = 0; // first send
1833 tunnelsend(c
->buf
, c
->length
, t
);
1838 // Throttle or Unthrottle a session
1840 // Throttle the data from/to through a session to no more than
1841 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1844 // If either value is -1, the current value is retained for that
1847 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1849 if (!session
[s
].opened
)
1850 return; // No-one home.
1852 if (!*session
[s
].user
)
1853 return; // User not logged in
1857 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1858 if (session
[s
].tbf_in
)
1859 free_tbf(session
[s
].tbf_in
);
1862 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1864 session
[s
].tbf_in
= 0;
1866 session
[s
].throttle_in
= rate_in
;
1871 int bytes
= rate_out
* 1024 / 8;
1872 if (session
[s
].tbf_out
)
1873 free_tbf(session
[s
].tbf_out
);
1876 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1878 session
[s
].tbf_out
= 0;
1880 session
[s
].throttle_out
= rate_out
;
1884 // add/remove filters from session (-1 = no change)
1885 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1887 if (!session
[s
].opened
)
1888 return; // No-one home.
1890 if (!*session
[s
].user
)
1891 return; // User not logged in
1894 if (filter_in
> MAXFILTER
) filter_in
= -1;
1895 if (filter_out
> MAXFILTER
) filter_out
= -1;
1896 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1897 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1901 if (session
[s
].filter_in
)
1902 ip_filters
[session
[s
].filter_in
- 1].used
--;
1905 ip_filters
[filter_in
- 1].used
++;
1907 session
[s
].filter_in
= filter_in
;
1910 if (filter_out
>= 0)
1912 if (session
[s
].filter_out
)
1913 ip_filters
[session
[s
].filter_out
- 1].used
--;
1916 ip_filters
[filter_out
- 1].used
++;
1918 session
[s
].filter_out
= filter_out
;
1922 // start tidy shutdown of session
1923 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1925 int walled_garden
= session
[s
].walled_garden
;
1926 bundleidt b
= session
[s
].bundle
;
1927 //delete routes only for last session in bundle (in case of MPPP)
1928 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1930 CSTAT(sessionshutdown
);
1932 if (!session
[s
].opened
)
1934 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1935 return; // not a live session
1938 if (!session
[s
].die
)
1940 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1941 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1942 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1943 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1946 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1948 // RADIUS Stop message
1949 uint16_t r
= radiusnew(s
);
1952 // stop, if not already trying
1953 if (radius
[r
].state
!= RADIUSSTOP
)
1955 radius
[r
].term_cause
= term_cause
;
1956 radius
[r
].term_msg
= reason
;
1957 radiussend(r
, RADIUSSTOP
);
1961 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1963 // Save counters to dump to accounting file
1964 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1965 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1969 { // IP allocated, clear and unroute
1972 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1974 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
1975 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
1978 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
1979 session
[s
].route
[r
].ip
= 0;
1982 if (session
[s
].ip_pool_index
== -1) // static ip
1984 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1990 // unroute IPv6, if setup
1991 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
1992 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1996 // This session was part of a bundle
1997 bundle
[b
].num_of_links
--;
1998 LOG(3, s
, 0, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
1999 if(bundle
[b
].num_of_links
== 0)
2002 LOG(3, s
, 0, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2006 // Adjust the members array to accomodate the new change
2007 uint8_t mem_num
= 0;
2008 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2009 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2012 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2013 if(bundle
[b
].members
[ml
] == s
)
2018 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2019 LOG(3, s
, 0, "MPPP: Adjusted member links array\n");
2022 cluster_send_bundle(b
);
2026 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2027 throttle_session(s
, 0, 0);
2031 controlt
*c
= controlnew(14); // sending CDN
2035 *(uint16_t *) buf
= htons(cdn_result
);
2036 *(uint16_t *) (buf
+2) = htons(cdn_error
);
2037 controlb(c
, 1, buf
, 4, 1);
2040 control16(c
, 1, cdn_result
, 1);
2042 control16(c
, 14, s
, 1); // assigned session (our end)
2043 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2046 // update filter refcounts
2047 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2048 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2051 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2052 sess_local
[s
].lcp
.restart
= 0;
2053 sess_local
[s
].ipcp
.restart
= 0;
2054 sess_local
[s
].ipv6cp
.restart
= 0;
2055 sess_local
[s
].ccp
.restart
= 0;
2057 cluster_send_session(s
);
2060 void sendipcp(sessionidt s
, tunnelidt t
)
2062 uint8_t buf
[MAXETHER
];
2066 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2068 if (!session
[s
].unique_id
)
2070 if (!++last_id
) ++last_id
; // skip zero
2071 session
[s
].unique_id
= last_id
;
2074 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2078 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2079 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2080 q
[4] = 3; // ip address option
2081 q
[5] = 6; // option length
2082 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2083 config
->bind_address
? config
->bind_address
:
2084 my_address
; // send my IP
2086 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2087 restart_timer(s
, ipcp
);
2090 void sendipv6cp(sessionidt s
, tunnelidt t
)
2092 uint8_t buf
[MAXETHER
];
2096 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2098 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2102 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2103 // only send one type
2105 *(uint16_t *) (q
+ 2) = htons(14);
2106 q
[4] = 1; // interface identifier option
2107 q
[5] = 10; // option length
2108 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2109 *(uint32_t *) (q
+ 10) = 0;
2112 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2113 restart_timer(s
, ipv6cp
);
2116 static void sessionclear(sessionidt s
)
2118 memset(&session
[s
], 0, sizeof(session
[s
]));
2119 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2120 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2122 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2123 session
[s
].next
= sessionfree
;
2127 // kill a session now
2128 void sessionkill(sessionidt s
, char *reason
)
2132 if (!session
[s
].opened
) // not alive
2135 if (session
[s
].next
)
2137 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2141 if (!session
[s
].die
)
2142 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2144 if (sess_local
[s
].radius
)
2145 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2147 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2149 cluster_send_session(s
);
2152 static void tunnelclear(tunnelidt t
)
2155 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2156 tunnel
[t
].state
= TUNNELFREE
;
2159 static void bundleclear(bundleidt b
)
2162 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2163 bundle
[b
].state
= BUNDLEFREE
;
2166 // kill a tunnel now
2167 static void tunnelkill(tunnelidt t
, char *reason
)
2174 tunnel
[t
].state
= TUNNELDIE
;
2176 // free control messages
2177 while ((c
= tunnel
[t
].controls
))
2179 controlt
* n
= c
->next
;
2180 tunnel
[t
].controls
= n
;
2181 tunnel
[t
].controlc
--;
2182 c
->next
= controlfree
;
2186 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2187 if (session
[s
].tunnel
== t
)
2188 sessionkill(s
, reason
);
2192 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2193 cli_tunnel_actions
[t
].action
= 0;
2194 cluster_send_tunnel(t
);
2197 // shut down a tunnel cleanly
2198 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2202 CSTAT(tunnelshutdown
);
2204 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2206 // never set up, can immediately kill
2207 tunnelkill(t
, reason
);
2210 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2213 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2214 if (session
[s
].tunnel
== t
)
2215 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2217 tunnel
[t
].state
= TUNNELDIE
;
2218 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2219 cluster_send_tunnel(t
);
2220 // TBA - should we wait for sessions to stop?
2223 controlt
*c
= controlnew(4); // sending StopCCN
2228 *(uint16_t *) buf
= htons(result
);
2229 *(uint16_t *) (buf
+2) = htons(error
);
2232 int m
= strlen(msg
);
2233 if (m
+ 4 > sizeof(buf
))
2234 m
= sizeof(buf
) - 4;
2236 memcpy(buf
+4, msg
, m
);
2240 controlb(c
, 1, buf
, l
, 1);
2243 control16(c
, 1, result
, 1);
2245 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2246 controladd(c
, 0, t
); // send the message
2250 // read and process packet on tunnel (UDP)
2251 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2253 uint8_t *chapresponse
= NULL
;
2254 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2255 uint8_t *p
= buf
+ 2;
2262 LOG_HEX(5, "UDP Data", buf
, len
);
2263 STAT(tunnel_rx_packets
);
2264 INC_STAT(tunnel_rx_bytes
, len
);
2267 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2268 STAT(tunnel_rx_errors
);
2271 if ((buf
[1] & 0x0F) != 2)
2273 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2274 STAT(tunnel_rx_errors
);
2279 l
= ntohs(*(uint16_t *) p
);
2282 t
= ntohs(*(uint16_t *) p
);
2284 s
= ntohs(*(uint16_t *) p
);
2286 if (s
>= MAXSESSION
)
2288 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2289 STAT(tunnel_rx_errors
);
2294 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2295 STAT(tunnel_rx_errors
);
2300 ns
= ntohs(*(uint16_t *) p
);
2302 nr
= ntohs(*(uint16_t *) p
);
2307 uint16_t o
= ntohs(*(uint16_t *) p
);
2312 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2313 STAT(tunnel_rx_errors
);
2318 // used to time out old tunnels
2319 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2320 tunnel
[t
].lastrec
= time_now
;
2324 uint16_t message
= 0xFFFF; // message type
2326 uint8_t mandatory
= 0;
2327 uint16_t asession
= 0; // assigned session
2328 uint32_t amagic
= 0; // magic number
2329 uint8_t aflags
= 0; // flags from last LCF
2330 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2331 char called
[MAXTEL
] = ""; // called number
2332 char calling
[MAXTEL
] = ""; // calling number
2334 if (!config
->cluster_iam_master
)
2336 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2340 // control messages must have bits 0x80|0x40|0x08
2341 // (type, length and sequence) set, and bits 0x02|0x01
2342 // (offset and priority) clear
2343 if ((*buf
& 0xCB) != 0xC8)
2345 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2346 STAT(tunnel_rx_errors
);
2350 // check for duplicate tunnel open message
2356 // Is this a duplicate of the first packet? (SCCRQ)
2358 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2360 if (tunnel
[i
].state
!= TUNNELOPENING
||
2361 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2362 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2365 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2370 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2371 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2373 // if no tunnel specified, assign one
2376 if (!(t
= new_tunnel()))
2378 LOG(1, 0, 0, "No more tunnels\n");
2379 STAT(tunnel_overflow
);
2383 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2384 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2385 tunnel
[t
].window
= 4; // default window
2386 STAT(tunnel_created
);
2387 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2388 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2391 // If the 'ns' just received is not the 'nr' we're
2392 // expecting, just send an ack and drop it.
2394 // if 'ns' is less, then we got a retransmitted packet.
2395 // if 'ns' is greater than missed a packet. Either way
2396 // we should ignore it.
2397 if (ns
!= tunnel
[t
].nr
)
2399 // is this the sequence we were expecting?
2400 STAT(tunnel_rx_errors
);
2401 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2402 t
, ns
, tunnel
[t
].nr
);
2404 if (l
) // Is this not a ZLB?
2409 // check sequence of this message
2411 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2412 // some to clear maybe?
2413 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2415 controlt
*c
= tunnel
[t
].controls
;
2416 tunnel
[t
].controls
= c
->next
;
2417 tunnel
[t
].controlc
--;
2418 c
->next
= controlfree
;
2421 tunnel
[t
].try = 0; // we have progress
2424 // receiver advance (do here so quoted correctly in any sends below)
2425 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2426 if (skip
< 0) skip
= 0;
2427 if (skip
< tunnel
[t
].controlc
)
2429 // some control packets can now be sent that were previous stuck out of window
2430 int tosend
= tunnel
[t
].window
- skip
;
2431 controlt
*c
= tunnel
[t
].controls
;
2439 tunnel
[t
].try = 0; // first send
2440 tunnelsend(c
->buf
, c
->length
, t
);
2445 if (!tunnel
[t
].controlc
)
2446 tunnel
[t
].retry
= 0; // caught up
2449 { // if not a null message
2454 // Default disconnect cause/message on receipt of CDN. Set to
2455 // more specific value from attribute 1 (result code) or 46
2456 // (disconnect cause) if present below.
2457 int disc_cause_set
= 0;
2458 int disc_cause
= TERM_NAS_REQUEST
;
2459 char const *disc_reason
= "Closed (Received CDN).";
2462 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2464 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2471 LOG(1, s
, t
, "Invalid length in AVP\n");
2472 STAT(tunnel_rx_errors
);
2477 if (flags
& 0x3C) // reserved bits, should be clear
2479 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2481 result
= 2; // general error
2482 error
= 3; // reserved field non-zero
2487 if (*(uint16_t *) (b
))
2489 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2491 result
= 2; // general error
2492 error
= 6; // generic vendor-specific error
2493 msg
= "unsupported vendor-specific";
2497 mtype
= ntohs(*(uint16_t *) (b
));
2505 // handle hidden AVPs
2506 if (!*config
->l2tp_secret
)
2508 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2510 result
= 2; // general error
2511 error
= 6; // generic vendor-specific error
2512 msg
= "secret not specified";
2515 if (!session
[s
].random_vector_length
)
2517 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2519 result
= 2; // general error
2520 error
= 6; // generic
2521 msg
= "no random vector";
2526 LOG(2, s
, t
, "Short hidden AVP.\n");
2528 result
= 2; // general error
2529 error
= 2; // length is wrong
2535 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2537 orig_len
= ntohs(*(uint16_t *) b
);
2538 if (orig_len
> n
+ 2)
2540 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2544 result
= 2; // general error
2545 error
= 2; // length is wrong
2554 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2555 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2559 case 0: // message type
2560 message
= ntohs(*(uint16_t *) b
);
2561 mandatory
= flags
& 0x80;
2562 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2564 case 1: // result code
2566 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2567 char const *resdesc
= "(unknown)";
2568 char const *errdesc
= NULL
;
2573 resdesc
= l2tp_stopccn_result_code(rescode
);
2574 cause
= TERM_LOST_SERVICE
;
2576 else if (message
== 14)
2578 resdesc
= l2tp_cdn_result_code(rescode
);
2580 cause
= TERM_LOST_CARRIER
;
2582 cause
= TERM_ADMIN_RESET
;
2585 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2588 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2589 errdesc
= l2tp_error_code(errcode
);
2590 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2593 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2595 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2597 disc_cause_set
= mtype
;
2598 disc_reason
= errdesc
? errdesc
: resdesc
;
2605 case 2: // protocol version
2607 version
= ntohs(*(uint16_t *) (b
));
2608 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2609 if (version
&& version
!= 0x0100)
2610 { // allow 0.0 and 1.0
2611 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2613 result
= 5; // unspported protocol version
2614 error
= 0x0100; // supported version
2620 case 3: // framing capabilities
2622 case 4: // bearer capabilities
2624 case 5: // tie breaker
2625 // We never open tunnels, so we don't care about tie breakers
2627 case 6: // firmware revision
2629 case 7: // host name
2630 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2631 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2632 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2633 // TBA - to send to RADIUS
2635 case 8: // vendor name
2636 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2637 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2638 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2640 case 9: // assigned tunnel
2641 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2642 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2644 case 10: // rx window
2645 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2646 if (!tunnel
[t
].window
)
2647 tunnel
[t
].window
= 1; // window of 0 is silly
2648 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2650 case 11: // Challenge
2652 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2653 build_chap_response(b
, 2, n
, &chapresponse
);
2656 case 13: // Response
2657 // Why did they send a response? We never challenge.
2658 LOG(2, s
, t
, " received unexpected challenge response\n");
2661 case 14: // assigned session
2662 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2663 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2665 case 15: // call serial number
2666 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2668 case 18: // bearer type
2669 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2672 case 19: // framing type
2673 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2676 case 21: // called number
2677 memset(called
, 0, sizeof(called
));
2678 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2679 LOG(4, s
, t
, " Called <%s>\n", called
);
2681 case 22: // calling number
2682 memset(calling
, 0, sizeof(calling
));
2683 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2684 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2688 case 24: // tx connect speed
2691 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2695 // AS5300s send connect speed as a string
2697 memset(tmp
, 0, sizeof(tmp
));
2698 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2699 session
[s
].tx_connect_speed
= atol(tmp
);
2701 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2703 case 38: // rx connect speed
2706 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2710 // AS5300s send connect speed as a string
2712 memset(tmp
, 0, sizeof(tmp
));
2713 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2714 session
[s
].rx_connect_speed
= atol(tmp
);
2716 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2718 case 25: // Physical Channel ID
2720 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2721 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2724 case 29: // Proxy Authentication Type
2726 uint16_t atype
= ntohs(*(uint16_t *)b
);
2727 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2730 case 30: // Proxy Authentication Name
2733 memset(authname
, 0, sizeof(authname
));
2734 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2735 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2739 case 31: // Proxy Authentication Challenge
2741 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2744 case 32: // Proxy Authentication ID
2746 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2747 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2750 case 33: // Proxy Authentication Response
2751 LOG(4, s
, t
, " Proxy Auth Response\n");
2753 case 27: // last sent lcp
2754 { // find magic number
2755 uint8_t *p
= b
, *e
= p
+ n
;
2756 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2758 if (*p
== 5 && p
[1] == 6) // Magic-Number
2759 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2760 else if (*p
== 7) // Protocol-Field-Compression
2761 aflags
|= SESSION_PFC
;
2762 else if (*p
== 8) // Address-and-Control-Field-Compression
2763 aflags
|= SESSION_ACFC
;
2768 case 28: // last recv lcp confreq
2770 case 26: // Initial Received LCP CONFREQ
2772 case 39: // seq required - we control it as an LNS anyway...
2774 case 36: // Random Vector
2775 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2776 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2777 if (n
> sizeof(session
[s
].random_vector
))
2778 n
= sizeof(session
[s
].random_vector
);
2779 memcpy(session
[s
].random_vector
, b
, n
);
2780 session
[s
].random_vector_length
= n
;
2782 case 46: // ppp disconnect cause
2785 uint16_t code
= ntohs(*(uint16_t *) b
);
2786 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2787 uint8_t dir
= *(b
+ 4);
2789 LOG(4, s
, t
, " PPP disconnect cause "
2790 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2791 code
, proto
, dir
, n
- 5, b
+ 5);
2793 disc_cause_set
= mtype
;
2797 case 1: // admin disconnect
2798 disc_cause
= TERM_ADMIN_RESET
;
2799 disc_reason
= "Administrative disconnect";
2801 case 3: // lcp terminate
2802 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2803 disc_cause
= TERM_USER_REQUEST
;
2804 disc_reason
= "Normal disconnection";
2806 case 4: // compulsory encryption unavailable
2807 if (dir
!= 1) break; // 1=refused by peer, 2=local
2808 disc_cause
= TERM_USER_ERROR
;
2809 disc_reason
= "Compulsory encryption refused";
2811 case 5: // lcp: fsm timeout
2812 disc_cause
= TERM_PORT_ERROR
;
2813 disc_reason
= "LCP: FSM timeout";
2815 case 6: // lcp: no recognisable lcp packets received
2816 disc_cause
= TERM_PORT_ERROR
;
2817 disc_reason
= "LCP: no recognisable LCP packets";
2819 case 7: // lcp: magic-no error (possibly looped back)
2820 disc_cause
= TERM_PORT_ERROR
;
2821 disc_reason
= "LCP: magic-no error (possible loop)";
2823 case 8: // lcp: echo request timeout
2824 disc_cause
= TERM_PORT_ERROR
;
2825 disc_reason
= "LCP: echo request timeout";
2827 case 13: // auth: fsm timeout
2828 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2829 disc_reason
= "Authentication: FSM timeout";
2831 case 15: // auth: unacceptable auth protocol
2832 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2833 disc_reason
= "Unacceptable authentication protocol";
2835 case 16: // auth: authentication failed
2836 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2837 disc_reason
= "Authentication failed";
2839 case 17: // ncp: fsm timeout
2840 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2841 disc_reason
= "NCP: FSM timeout";
2843 case 18: // ncp: no ncps available
2844 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2845 disc_reason
= "NCP: no NCPs available";
2847 case 19: // ncp: failure to converge on acceptable address
2848 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2849 disc_reason
= (dir
== 1)
2850 ? "NCP: too many Configure-Naks received from peer"
2851 : "NCP: too many Configure-Naks sent to peer";
2853 case 20: // ncp: user not permitted to use any address
2854 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2855 disc_reason
= (dir
== 1)
2856 ? "NCP: local link address not acceptable to peer"
2857 : "NCP: remote link address not acceptable";
2864 static char e
[] = "unknown AVP 0xXXXX";
2865 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2867 result
= 2; // general error
2868 error
= 8; // unknown mandatory AVP
2869 sprintf((msg
= e
) + 14, "%04x", mtype
);
2876 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2880 case 1: // SCCRQ - Start Control Connection Request
2881 tunnel
[t
].state
= TUNNELOPENING
;
2882 if (main_quit
!= QUIT_SHUTDOWN
)
2884 controlt
*c
= controlnew(2); // sending SCCRP
2885 control16(c
, 2, version
, 1); // protocol version
2886 control32(c
, 3, 3, 1); // framing
2887 controls(c
, 7, hostname
, 1); // host name
2888 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2889 control16(c
, 9, t
, 1); // assigned tunnel
2890 controladd(c
, 0, t
); // send the resply
2894 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2898 tunnel
[t
].state
= TUNNELOPEN
;
2899 tunnel
[t
].lastrec
= time_now
;
2902 tunnel
[t
].state
= TUNNELOPEN
;
2903 tunnel
[t
].lastrec
= time_now
;
2904 controlnull(t
); // ack
2907 controlnull(t
); // ack
2908 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2911 controlnull(t
); // simply ACK
2923 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2925 controlt
*c
= controlnew(11); // ICRP
2928 sessionfree
= session
[s
].next
;
2929 memset(&session
[s
], 0, sizeof(session
[s
]));
2931 if (s
> config
->cluster_highest_sessionid
)
2932 config
->cluster_highest_sessionid
= s
;
2934 session
[s
].opened
= time_now
;
2935 session
[s
].tunnel
= t
;
2936 session
[s
].far
= asession
;
2937 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2938 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2939 control16(c
, 14, s
, 1); // assigned session
2940 controladd(c
, asession
, t
); // send the reply
2942 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2943 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2945 session
[s
].ppp
.phase
= Establish
;
2946 session
[s
].ppp
.lcp
= Starting
;
2948 STAT(session_created
);
2953 controlt
*c
= controlnew(14); // CDN
2956 STAT(session_overflow
);
2957 LOG(1, 0, t
, "No free sessions\n");
2958 control16(c
, 1, 4, 0); // temporary lack of resources
2961 control16(c
, 1, 2, 7); // shutting down, try another
2963 controladd(c
, asession
, t
); // send the message
2970 if (amagic
== 0) amagic
= time_now
;
2971 session
[s
].magic
= amagic
; // set magic number
2972 session
[s
].flags
= aflags
; // set flags received
2973 session
[s
].mru
= PPPoE_MRU
; // default
2974 controlnull(t
); // ack
2977 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
2978 sess_local
[s
].ppp_mru
= MRU
;
2980 // Set multilink options before sending initial LCP packet
2981 sess_local
[s
].mp_mrru
= 1614;
2982 sess_local
[s
].mp_epdis
= config
->bind_address
? config
->bind_address
: my_address
;
2985 change_state(s
, lcp
, RequestSent
);
2989 controlnull(t
); // ack
2990 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
2993 LOG(1, s
, t
, "Missing message type\n");
2996 STAT(tunnel_rx_errors
);
2998 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3000 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3003 if (chapresponse
) free(chapresponse
);
3004 cluster_send_tunnel(t
);
3008 LOG(4, s
, t
, " Got a ZLB ack\n");
3015 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3016 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3017 { // HDLC address header, discard
3023 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3024 STAT(tunnel_rx_errors
);
3034 proto
= ntohs(*(uint16_t *) p
);
3039 if (s
&& !session
[s
].opened
) // Is something wrong??
3041 if (!config
->cluster_iam_master
)
3043 // Pass it off to the master to deal with..
3044 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3049 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3050 STAT(tunnel_rx_errors
);
3054 if (proto
== PPPPAP
)
3056 session
[s
].last_packet
= time_now
;
3057 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3058 processpap(s
, t
, p
, l
);
3060 else if (proto
== PPPCHAP
)
3062 session
[s
].last_packet
= time_now
;
3063 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3064 processchap(s
, t
, p
, l
);
3066 else if (proto
== PPPLCP
)
3068 session
[s
].last_packet
= time_now
;
3069 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3070 processlcp(s
, t
, p
, l
);
3072 else if (proto
== PPPIPCP
)
3074 session
[s
].last_packet
= time_now
;
3075 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3076 processipcp(s
, t
, p
, l
);
3078 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3080 session
[s
].last_packet
= time_now
;
3081 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3082 processipv6cp(s
, t
, p
, l
);
3084 else if (proto
== PPPCCP
)
3086 session
[s
].last_packet
= time_now
;
3087 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3088 processccp(s
, t
, p
, l
);
3090 else if (proto
== PPPIP
)
3094 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3095 return; // closing session, PPP not processed
3098 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3099 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3101 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3105 processipin(s
, t
, p
, l
);
3107 else if (proto
== PPPMP
)
3111 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3112 return; // closing session, PPP not processed
3115 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3116 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3118 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3122 processmpin(s
, t
, p
, l
);
3124 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3128 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3129 return; // closing session, PPP not processed
3132 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3133 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3135 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3139 processipv6in(s
, t
, p
, l
);
3141 else if (session
[s
].ppp
.lcp
== Opened
)
3143 session
[s
].last_packet
= time_now
;
3144 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3145 protoreject(s
, t
, p
, l
, proto
);
3149 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3150 proto
, ppp_state(session
[s
].ppp
.lcp
));
3155 // read and process packet on tun
3156 static void processtun(uint8_t * buf
, int len
)
3158 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3159 STAT(tun_rx_packets
);
3160 INC_STAT(tun_rx_bytes
, len
);
3168 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3169 STAT(tun_rx_errors
);
3173 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3174 processipout(buf
, len
);
3175 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3176 && config
->ipv6_prefix
.s6_addr
[0])
3177 processipv6out(buf
, len
);
3182 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3183 // that we look at the whole of the tunnel, radius and session tables
3185 static void regular_cleanups(double period
)
3187 // Next tunnel, radius and session to check for actions on.
3188 static tunnelidt t
= 0;
3190 static sessionidt s
= 0;
3203 // divide up tables into slices based on the last run
3204 t_slice
= config
->cluster_highest_tunnelid
* period
;
3205 r_slice
= (MAXRADIUS
- 1) * period
;
3206 s_slice
= config
->cluster_highest_sessionid
* period
;
3210 else if (t_slice
> config
->cluster_highest_tunnelid
)
3211 t_slice
= config
->cluster_highest_tunnelid
;
3215 else if (r_slice
> (MAXRADIUS
- 1))
3216 r_slice
= MAXRADIUS
- 1;
3220 else if (s_slice
> config
->cluster_highest_sessionid
)
3221 s_slice
= config
->cluster_highest_sessionid
;
3223 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3225 for (i
= 0; i
< t_slice
; i
++)
3228 if (t
> config
->cluster_highest_tunnelid
)
3231 // check for expired tunnels
3232 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3234 STAT(tunnel_timeout
);
3235 tunnelkill(t
, "Expired");
3239 // check for message resend
3240 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3242 // resend pending messages as timeout on reply
3243 if (tunnel
[t
].retry
<= TIME
)
3245 controlt
*c
= tunnel
[t
].controls
;
3246 uint16_t w
= tunnel
[t
].window
;
3247 tunnel
[t
].try++; // another try
3248 if (tunnel
[t
].try > 5)
3249 tunnelkill(t
, "Timeout on control message"); // game over
3253 tunnelsend(c
->buf
, c
->length
, t
);
3261 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3263 controlt
*c
= controlnew(6); // sending HELLO
3264 controladd(c
, 0, t
); // send the message
3265 LOG(3, 0, t
, "Sending HELLO message\n");
3269 // Check for tunnel changes requested from the CLI
3270 if ((a
= cli_tunnel_actions
[t
].action
))
3272 cli_tunnel_actions
[t
].action
= 0;
3273 if (a
& CLI_TUN_KILL
)
3275 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3276 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3282 for (i
= 0; i
< r_slice
; i
++)
3288 if (!radius
[r
].state
)
3291 if (radius
[r
].retry
<= TIME
)
3298 for (i
= 0; i
< s_slice
; i
++)
3301 if (s
> config
->cluster_highest_sessionid
)
3304 if (!session
[s
].opened
) // Session isn't in use
3307 // check for expired sessions
3310 if (session
[s
].die
<= TIME
)
3312 sessionkill(s
, "Expired");
3319 if (sess_local
[s
].lcp
.restart
<= time_now
)
3321 int next_state
= session
[s
].ppp
.lcp
;
3322 switch (session
[s
].ppp
.lcp
)
3326 next_state
= RequestSent
;
3329 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3331 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3332 sendlcp(s
, session
[s
].tunnel
);
3333 change_state(s
, lcp
, next_state
);
3337 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3338 STAT(session_timeout
);
3348 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3350 int next_state
= session
[s
].ppp
.ipcp
;
3351 switch (session
[s
].ppp
.ipcp
)
3355 next_state
= RequestSent
;
3358 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3360 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3361 sendipcp(s
, session
[s
].tunnel
);
3362 change_state(s
, ipcp
, next_state
);
3366 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3367 STAT(session_timeout
);
3377 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3379 int next_state
= session
[s
].ppp
.ipv6cp
;
3380 switch (session
[s
].ppp
.ipv6cp
)
3384 next_state
= RequestSent
;
3387 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3389 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3390 sendipv6cp(s
, session
[s
].tunnel
);
3391 change_state(s
, ipv6cp
, next_state
);
3395 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3396 change_state(s
, ipv6cp
, Stopped
);
3403 if (sess_local
[s
].ccp
.restart
<= time_now
)
3405 int next_state
= session
[s
].ppp
.ccp
;
3406 switch (session
[s
].ppp
.ccp
)
3410 next_state
= RequestSent
;
3413 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3415 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3416 sendccp(s
, session
[s
].tunnel
);
3417 change_state(s
, ccp
, next_state
);
3421 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3422 change_state(s
, ccp
, Stopped
);
3429 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3430 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3432 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3433 STAT(session_timeout
);
3438 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3439 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3440 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3442 uint8_t b
[MAXETHER
];
3444 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3448 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3449 *(uint16_t *)(q
+ 2) = htons(8); // Length
3450 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3452 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3453 (int)(time_now
- session
[s
].last_packet
));
3454 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3455 sess_local
[s
].last_echo
= time_now
;
3459 // Drop sessions who have reached session_timeout seconds
3460 if (session
[s
].session_timeout
)
3462 bundleidt bid
= session
[s
].bundle
;
3465 if (time_now
- bundle
[bid
].last_check
>= 1)
3467 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3468 bundle
[bid
].last_check
= time_now
;
3469 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3472 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3474 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3481 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3483 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3489 // Drop sessions who have reached idle_timeout seconds
3490 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3492 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3493 STAT(session_timeout
);
3498 // Check for actions requested from the CLI
3499 if ((a
= cli_session_actions
[s
].action
))
3503 cli_session_actions
[s
].action
= 0;
3504 if (a
& CLI_SESS_KILL
)
3506 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3507 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3508 a
= 0; // dead, no need to check for other actions
3512 if (a
& CLI_SESS_NOSNOOP
)
3514 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3515 session
[s
].snoop_ip
= 0;
3516 session
[s
].snoop_port
= 0;
3520 else if (a
& CLI_SESS_SNOOP
)
3522 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3523 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3524 cli_session_actions
[s
].snoop_port
);
3526 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3527 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3532 if (a
& CLI_SESS_NOTHROTTLE
)
3534 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3535 throttle_session(s
, 0, 0);
3539 else if (a
& CLI_SESS_THROTTLE
)
3541 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3542 cli_session_actions
[s
].throttle_in
,
3543 cli_session_actions
[s
].throttle_out
);
3545 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3550 if (a
& CLI_SESS_NOFILTER
)
3552 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3553 filter_session(s
, 0, 0);
3557 else if (a
& CLI_SESS_FILTER
)
3559 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3560 cli_session_actions
[s
].filter_in
,
3561 cli_session_actions
[s
].filter_out
);
3563 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3569 cluster_send_session(s
);
3572 // RADIUS interim accounting
3573 if (config
->radius_accounting
&& config
->radius_interim
> 0
3574 && session
[s
].ip
&& !session
[s
].walled_garden
3575 && !sess_local
[s
].radius
// RADIUS already in progress
3576 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3577 && session
[s
].flags
& SESSION_STARTED
)
3579 int rad
= radiusnew(s
);
3582 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3583 STAT(radius_overflow
);
3587 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3588 session
[s
].user
, session
[s
].unique_id
);
3590 radiussend(rad
, RADIUSINTERIM
);
3591 sess_local
[s
].last_interim
= time_now
;
3596 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3597 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3601 // Are we in the middle of a tunnel update, or radius
3604 static int still_busy(void)
3607 static clockt last_talked
= 0;
3608 static clockt start_busy_wait
= 0;
3611 static time_t stopped_bgp
= 0;
3616 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3618 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3619 if (bgp_peers
[i
].state
== Established
)
3620 bgp_stop(&bgp_peers
[i
]);
3622 stopped_bgp
= time_now
;
3624 if (!config
->cluster_iam_master
)
3626 // we don't want to become master
3627 cluster_send_ping(0);
3633 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3638 if (!config
->cluster_iam_master
)
3641 if (main_quit
== QUIT_SHUTDOWN
)
3643 static int dropped
= 0;
3648 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3649 for (i
= 1; i
< MAXTUNNEL
; i
++)
3650 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3651 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3657 if (start_busy_wait
== 0)
3658 start_busy_wait
= TIME
;
3660 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3662 if (!tunnel
[i
].controlc
)
3665 if (last_talked
!= TIME
)
3667 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3673 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3674 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3676 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3680 for (i
= 1; i
< MAXRADIUS
; i
++)
3682 if (radius
[i
].state
== RADIUSNULL
)
3684 if (radius
[i
].state
== RADIUSWAIT
)
3687 if (last_talked
!= TIME
)
3689 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3699 # include <sys/epoll.h>
3701 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3702 # include "fake_epoll.h"
3705 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3708 // additional polled fds
3710 # define EXTRA_FDS BGP_NUM_PEERS
3712 # define EXTRA_FDS 0
3715 // main loop - gets packets on tun or udp and processes them
3716 static void mainloop(void)
3720 clockt next_cluster_ping
= 0; // send initial ping immediately
3721 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3722 int maxevent
= sizeof(events
)/sizeof(*events
);
3724 if ((epollfd
= epoll_create(maxevent
)) < 0)
3726 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3730 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3731 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3733 /* setup our fds to poll for input */
3735 static struct event_data d
[BASE_FDS
];
3736 struct epoll_event e
;
3743 d
[i
].type
= FD_TYPE_CLI
;
3744 e
.data
.ptr
= &d
[i
++];
3745 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3748 d
[i
].type
= FD_TYPE_CLUSTER
;
3749 e
.data
.ptr
= &d
[i
++];
3750 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3752 d
[i
].type
= FD_TYPE_TUN
;
3753 e
.data
.ptr
= &d
[i
++];
3754 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3756 d
[i
].type
= FD_TYPE_UDP
;
3757 e
.data
.ptr
= &d
[i
++];
3758 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3760 d
[i
].type
= FD_TYPE_CONTROL
;
3761 e
.data
.ptr
= &d
[i
++];
3762 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3764 d
[i
].type
= FD_TYPE_DAE
;
3765 e
.data
.ptr
= &d
[i
++];
3766 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3768 d
[i
].type
= FD_TYPE_NETLINK
;
3769 e
.data
.ptr
= &d
[i
++];
3770 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3774 signal(SIGPIPE
, SIG_IGN
);
3775 bgp_setup(config
->as_number
);
3776 if (config
->bind_address
)
3777 bgp_add_route(config
->bind_address
, 0xffffffff);
3779 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3781 if (config
->neighbour
[i
].name
[0])
3782 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3783 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3784 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
3785 0); /* 0 = routing disabled */
3789 while (!main_quit
|| still_busy())
3799 config
->reload_config
++;
3802 if (config
->reload_config
)
3804 config
->reload_config
= 0;
3812 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3813 STAT(select_called
);
3818 if (errno
== EINTR
||
3819 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3822 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3828 struct sockaddr_in addr
;
3829 struct in_addr local
;
3834 int cluster_ready
= 0;
3837 int cluster_pkts
= 0;
3839 uint32_t bgp_events
[BGP_NUM_PEERS
];
3840 memset(bgp_events
, 0, sizeof(bgp_events
));
3843 for (c
= n
, i
= 0; i
< c
; i
++)
3845 struct event_data
*d
= events
[i
].data
.ptr
;
3849 case FD_TYPE_CLI
: // CLI connections
3853 alen
= sizeof(addr
);
3854 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3860 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3866 // these are handled below, with multiple interleaved reads
3867 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3868 case FD_TYPE_TUN
: tun_ready
++; break;
3869 case FD_TYPE_UDP
: udp_ready
++; break;
3871 case FD_TYPE_CONTROL
: // nsctl commands
3872 alen
= sizeof(addr
);
3873 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3874 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3878 case FD_TYPE_DAE
: // DAE requests
3879 alen
= sizeof(addr
);
3880 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3881 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3885 case FD_TYPE_RADIUS
: // RADIUS response
3886 alen
= sizeof(addr
);
3887 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3888 if (s
>= 0 && config
->cluster_iam_master
)
3890 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3891 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3892 processrad(buf
, s
, d
->index
);
3894 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3895 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3903 bgp_events
[d
->index
] = events
[i
].events
;
3908 case FD_TYPE_NETLINK
:
3910 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
3911 s
= netlink_recv(buf
, sizeof(buf
));
3912 if (nh
->nlmsg_type
== NLMSG_ERROR
)
3914 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
3917 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
3919 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
3924 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
3929 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
);
3935 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3940 bgp_process(bgp_events
);
3943 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3948 alen
= sizeof(addr
);
3949 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3951 processudp(buf
, s
, &addr
);
3964 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3979 alen
= sizeof(addr
);
3980 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3982 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3993 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3994 STAT(multi_read_used
);
3996 if (c
>= config
->multi_read_count
)
3998 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3999 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
4001 STAT(multi_read_exceeded
);
4007 /* no event received, but timers could still have expired */
4008 bgp_process_peers_timers();
4013 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4015 // Log current traffic stats
4016 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4017 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4018 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4019 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4020 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4022 udp_tx
= udp_rx
= 0;
4023 udp_rx_pkt
= eth_rx_pkt
= 0;
4024 eth_tx
= eth_rx
= 0;
4027 if (config
->dump_speed
)
4028 printf("%s\n", config
->bandwidth
);
4030 // Update the internal time counter
4031 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4035 struct param_timer p
= { time_now
};
4036 run_plugins(PLUGIN_TIMER
, &p
);
4040 // Runs on every machine (master and slaves).
4041 if (next_cluster_ping
<= TIME
)
4043 // Check to see which of the cluster is still alive..
4045 cluster_send_ping(basetime
); // Only does anything if we're a slave
4046 cluster_check_master(); // ditto.
4048 cluster_heartbeat(); // Only does anything if we're a master.
4049 cluster_check_slaves(); // ditto.
4051 master_update_counts(); // If we're a slave, send our byte counters to our master.
4053 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4054 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4056 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4059 if (!config
->cluster_iam_master
)
4062 // Run token bucket filtering queue..
4063 // Only run it every 1/10th of a second.
4065 static clockt last_run
= 0;
4066 if (last_run
!= TIME
)
4073 // Handle timeouts, retries etc.
4075 static double last_clean
= 0;
4079 TIME
= now(&this_clean
);
4080 diff
= this_clean
- last_clean
;
4082 // Run during idle time (after we've handled
4083 // all incoming packets) or every 1/10th sec
4084 if (!more
|| diff
> 0.1)
4086 regular_cleanups(diff
);
4087 last_clean
= this_clean
;
4091 if (*config
->accounting_dir
)
4093 static clockt next_acct
= 0;
4094 static clockt next_shut_acct
= 0;
4096 if (next_acct
<= TIME
)
4098 // Dump accounting data
4099 next_acct
= TIME
+ ACCT_TIME
;
4100 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4103 else if (next_shut_acct
<= TIME
)
4105 // Dump accounting data for shutdown sessions
4106 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4113 // Are we the master and shutting down??
4114 if (config
->cluster_iam_master
)
4115 cluster_heartbeat(); // Flush any queued changes..
4117 // Ok. Notify everyone we're shutting down. If we're
4118 // the master, this will force an election.
4119 cluster_send_ping(0);
4122 // Important!!! We MUST not process any packets past this point!
4123 LOG(1, 0, 0, "Shutdown complete\n");
4126 static void stripdomain(char *host
)
4130 if ((p
= strchr(host
, '.')))
4136 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4142 while (fgets(buf
, sizeof(buf
), resolv
))
4144 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4147 if (!isspace(buf
[6]))
4151 while (isspace(*b
)) b
++;
4156 while (*b
&& !isspace(*b
)) b
++;
4158 if (buf
[0] == 'd') // domain is canonical
4164 // first search line
4167 // hold, may be subsequent domain line
4168 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4179 int hl
= strlen(host
);
4180 int dl
= strlen(domain
);
4181 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4182 host
[hl
-dl
- 1] = 0;
4186 *p
= 0; // everything after first dot
4191 // Init data structures
4192 static void initdata(int optdebug
, char *optconfig
)
4196 if (!(config
= shared_malloc(sizeof(configt
))))
4198 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4202 memset(config
, 0, sizeof(configt
));
4203 time(&config
->start_time
);
4204 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4205 config
->debug
= optdebug
;
4206 config
->num_tbfs
= MAXTBFS
;
4207 config
->rl_rate
= 28; // 28kbps
4208 config
->cluster_mcast_ttl
= 1;
4209 config
->cluster_master_min_adv
= 1;
4210 config
->ppp_restart_time
= 3;
4211 config
->ppp_max_configure
= 10;
4212 config
->ppp_max_failure
= 5;
4213 config
->kill_timedout_sessions
= 1;
4214 strcpy(config
->random_device
, RANDOMDEVICE
);
4216 log_stream
= stderr
;
4219 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4221 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4224 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4227 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4229 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4232 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4234 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4237 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4239 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4242 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4244 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4247 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4249 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4253 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4255 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4259 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4261 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4265 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4267 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4271 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4273 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4276 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4278 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4280 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4283 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4285 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4287 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4290 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4292 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4293 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4294 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4295 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4296 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4298 // Put all the sessions on the free list marked as undefined.
4299 for (i
= 1; i
< MAXSESSION
; i
++)
4301 session
[i
].next
= i
+ 1;
4302 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4304 session
[MAXSESSION
- 1].next
= 0;
4307 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4308 for (i
= 1; i
< MAXTUNNEL
; i
++)
4309 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4311 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4312 bundle
[i
].state
= BUNDLEUNDEF
;
4317 if (!*config
->hostname
)
4319 // Grab my hostname unless it's been specified
4320 gethostname(hostname
, sizeof(hostname
));
4321 stripdomain(hostname
);
4324 strcpy(hostname
, config
->hostname
);
4327 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4330 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4332 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4338 static int assign_ip_address(sessionidt s
)
4342 time_t best_time
= time_now
;
4343 char *u
= session
[s
].user
;
4347 CSTAT(assign_ip_address
);
4349 for (i
= 1; i
< ip_pool_size
; i
++)
4351 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4354 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4361 if (ip_address_pool
[i
].last
< best_time
)
4364 if (!(best_time
= ip_address_pool
[i
].last
))
4365 break; // never used, grab this one
4371 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4375 session
[s
].ip
= ip_address_pool
[best
].address
;
4376 session
[s
].ip_pool_index
= best
;
4377 ip_address_pool
[best
].assigned
= 1;
4378 ip_address_pool
[best
].last
= time_now
;
4379 ip_address_pool
[best
].session
= s
;
4380 if (session
[s
].walled_garden
)
4381 /* Don't track addresses of users in walled garden (note: this
4382 means that their address isn't "sticky" even if they get
4384 ip_address_pool
[best
].user
[0] = 0;
4386 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4389 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4390 reuse
? "Reusing" : "Allocating", best
);
4395 static void free_ip_address(sessionidt s
)
4397 int i
= session
[s
].ip_pool_index
;
4400 CSTAT(free_ip_address
);
4403 return; // what the?
4405 if (i
< 0) // Is this actually part of the ip pool?
4409 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4411 ip_address_pool
[i
].assigned
= 0;
4412 ip_address_pool
[i
].session
= 0;
4413 ip_address_pool
[i
].last
= time_now
;
4417 // Fsck the address pool against the session table.
4418 // Normally only called when we become a master.
4420 // This isn't perfect: We aren't keep tracking of which
4421 // users used to have an IP address.
4423 void rebuild_address_pool(void)
4428 // Zero the IP pool allocation, and build
4429 // a map from IP address to pool index.
4430 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4432 ip_address_pool
[i
].assigned
= 0;
4433 ip_address_pool
[i
].session
= 0;
4434 if (!ip_address_pool
[i
].address
)
4437 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4440 for (i
= 0; i
< MAXSESSION
; ++i
)
4443 if (!(session
[i
].opened
&& session
[i
].ip
))
4446 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4448 if (session
[i
].ip_pool_index
< 0)
4450 // Not allocated out of the pool.
4451 if (ipid
< 1) // Not found in the pool either? good.
4454 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4455 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4457 // Fall through and process it as part of the pool.
4461 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4463 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4465 session
[i
].ip_pool_index
= ipid
;
4469 ip_address_pool
[ipid
].assigned
= 1;
4470 ip_address_pool
[ipid
].session
= i
;
4471 ip_address_pool
[ipid
].last
= time_now
;
4472 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4473 session
[i
].ip_pool_index
= ipid
;
4474 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4479 // Fix the address pool to match a changed session.
4480 // (usually when the master sends us an update).
4481 static void fix_address_pool(int sid
)
4485 ipid
= session
[sid
].ip_pool_index
;
4487 if (ipid
> ip_pool_size
)
4488 return; // Ignore it. rebuild_address_pool will fix it up.
4490 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4491 return; // Just ignore it. rebuild_address_pool will take care of it.
4493 ip_address_pool
[ipid
].assigned
= 1;
4494 ip_address_pool
[ipid
].session
= sid
;
4495 ip_address_pool
[ipid
].last
= time_now
;
4496 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4500 // Add a block of addresses to the IP pool to hand out.
4502 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4506 prefixlen
= 32; // Host route only.
4508 addr
&= 0xffffffff << (32 - prefixlen
);
4510 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4513 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4515 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4516 continue; // Skip 0 and broadcast addresses.
4518 ip_address_pool
[ip_pool_size
].address
= i
;
4519 ip_address_pool
[ip_pool_size
].assigned
= 0;
4521 if (ip_pool_size
>= MAXIPPOOL
)
4523 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4529 // Initialize the IP address pool
4530 static void initippool()
4535 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4537 if (!(f
= fopen(IPPOOLFILE
, "r")))
4539 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4543 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4546 buf
[4095] = 0; // Force it to be zero terminated/
4548 if (*buf
== '#' || *buf
== '\n')
4549 continue; // Skip comments / blank lines
4550 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4551 if ((p
= (char *)strchr(buf
, ':')))
4555 src
= inet_addr(buf
);
4556 if (src
== INADDR_NONE
)
4558 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4561 // This entry is for a specific IP only
4562 if (src
!= config
->bind_address
)
4567 if ((p
= (char *)strchr(pool
, '/')))
4571 in_addr_t start
= 0;
4573 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4575 if (!*p
|| !(numbits
= atoi(p
)))
4577 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4580 start
= ntohl(inet_addr(pool
));
4582 // Add a static route for this pool
4583 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4584 fmtaddr(htonl(start
), 0), numbits
);
4586 routeset(0, start
, numbits
, 0, 1);
4588 add_to_ip_pool(start
, numbits
);
4592 // It's a single ip address
4593 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4597 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4600 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4602 struct sockaddr_in snoop_addr
= {0};
4603 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4606 snoop_addr
.sin_family
= AF_INET
;
4607 snoop_addr
.sin_addr
.s_addr
= destination
;
4608 snoop_addr
.sin_port
= ntohs(port
);
4610 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4611 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4612 htons(snoop_addr
.sin_port
));
4614 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4615 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4617 STAT(packets_snooped
);
4620 static int dump_session(FILE **f
, sessiont
*s
)
4622 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4627 char filename
[1024];
4629 time_t now
= time(NULL
);
4631 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4632 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4634 if (!(*f
= fopen(filename
, "w")))
4636 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4640 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4641 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4646 "# format: username ip qos uptxoctets downrxoctets\n",
4648 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4653 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4654 fprintf(*f
, "%s %s %d %u %u\n",
4655 s
->user
, // username
4656 fmtaddr(htonl(s
->ip
), 0), // ip
4657 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4658 (uint32_t) s
->cin_delta
, // uptxoctets
4659 (uint32_t) s
->cout_delta
); // downrxoctets
4661 s
->cin_delta
= s
->cout_delta
= 0;
4666 static void dump_acct_info(int all
)
4672 CSTAT(dump_acct_info
);
4676 for (i
= 0; i
< shut_acct_n
; i
++)
4677 dump_session(&f
, &shut_acct
[i
]);
4683 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4684 dump_session(&f
, &session
[i
]);
4691 int main(int argc
, char *argv
[])
4695 char *optconfig
= CONFIGFILE
;
4697 time(&basetime
); // start clock
4700 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4705 if (fork()) exit(0);
4707 freopen("/dev/null", "r", stdin
);
4708 freopen("/dev/null", "w", stdout
);
4709 freopen("/dev/null", "w", stderr
);
4718 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4721 printf("Args are:\n"
4722 "\t-d\t\tDetach from terminal\n"
4723 "\t-c <file>\tConfig file\n"
4724 "\t-h <hostname>\tForce hostname\n"
4732 // Start the timer routine off
4734 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4737 initdata(optdebug
, optconfig
);
4742 init_tbf(config
->num_tbfs
);
4744 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4745 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4746 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4749 rlim
.rlim_cur
= RLIM_INFINITY
;
4750 rlim
.rlim_max
= RLIM_INFINITY
;
4751 // Remove the maximum core size
4752 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4753 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4755 // Make core dumps go to /tmp
4759 if (config
->scheduler_fifo
)
4762 struct sched_param params
= {0};
4763 params
.sched_priority
= 1;
4765 if (get_nprocs() < 2)
4767 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4768 config
->scheduler_fifo
= 0;
4772 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4774 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4778 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4779 config
->scheduler_fifo
= 0;
4786 /* Set up the cluster communications port. */
4787 if (cluster_init() < 0)
4791 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4799 unsigned seed
= time_now
^ getpid();
4800 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4804 signal(SIGHUP
, sighup_handler
);
4805 signal(SIGCHLD
, sigchild_handler
);
4806 signal(SIGTERM
, shutdown_handler
);
4807 signal(SIGINT
, shutdown_handler
);
4808 signal(SIGQUIT
, shutdown_handler
);
4810 // Prevent us from getting paged out
4811 if (config
->lock_pages
)
4813 if (!mlockall(MCL_CURRENT
))
4814 LOG(1, 0, 0, "Locking pages into memory\n");
4816 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4821 /* remove plugins (so cleanup code gets run) */
4824 // Remove the PID file if we wrote it
4825 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4826 unlink(config
->pid_file
);
4828 /* kill CLI children */
4829 signal(SIGTERM
, SIG_IGN
);
4834 static void sighup_handler(int sig
)
4839 static void shutdown_handler(int sig
)
4841 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4844 static void sigchild_handler(int sig
)
4846 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4850 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4853 *challenge_response
= NULL
;
4855 if (!*config
->l2tp_secret
)
4857 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4861 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4863 *challenge_response
= calloc(17, 1);
4866 MD5_Update(&ctx
, &id
, 1);
4867 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4868 MD5_Update(&ctx
, challenge
, challenge_length
);
4869 MD5_Final(*challenge_response
, &ctx
);
4874 static int facility_value(char *name
)
4877 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4879 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4880 return facilitynames
[i
].c_val
;
4885 static void update_config()
4889 static int timeout
= 0;
4890 static int interval
= 0;
4897 if (log_stream
!= stderr
)
4903 if (*config
->log_filename
)
4905 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4907 char *p
= config
->log_filename
+ 7;
4910 openlog("l2tpns", LOG_PID
, facility_value(p
));
4914 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4916 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4918 fseek(log_stream
, 0, SEEK_END
);
4919 setbuf(log_stream
, NULL
);
4923 log_stream
= stderr
;
4924 setbuf(log_stream
, NULL
);
4930 log_stream
= stderr
;
4931 setbuf(log_stream
, NULL
);
4934 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4935 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4937 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4938 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4939 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4941 // reset MRU/MSS globals
4942 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4943 if (MRU
> PPPoE_MRU
)
4946 MSS
= MRU
- TCP_HDRS
;
4949 config
->numradiusservers
= 0;
4950 for (i
= 0; i
< MAXRADSERVER
; i
++)
4951 if (config
->radiusserver
[i
])
4953 config
->numradiusservers
++;
4954 // Set radius port: if not set, take the port from the
4955 // first radius server. For the first radius server,
4956 // take the #defined default value from l2tpns.h
4958 // test twice, In case someone works with
4959 // a secondary radius server without defining
4960 // a primary one, this will work even then.
4961 if (i
> 0 && !config
->radiusport
[i
])
4962 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4963 if (!config
->radiusport
[i
])
4964 config
->radiusport
[i
] = RADPORT
;
4967 if (!config
->numradiusservers
)
4968 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4970 // parse radius_authtypes_s
4971 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4972 p
= config
->radius_authtypes_s
;
4975 char *s
= strpbrk(p
, " \t,");
4981 while (*s
== ' ' || *s
== '\t')
4988 if (!strncasecmp("chap", p
, strlen(p
)))
4990 else if (!strncasecmp("pap", p
, strlen(p
)))
4993 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4995 config
->radius_authtypes
|= type
;
4996 if (!config
->radius_authprefer
)
4997 config
->radius_authprefer
= type
;
5002 if (!config
->radius_authtypes
)
5004 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5005 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5008 // normalise radius_authtypes_s
5009 if (config
->radius_authprefer
== AUTHPAP
)
5011 strcpy(config
->radius_authtypes_s
, "pap");
5012 if (config
->radius_authtypes
& AUTHCHAP
)
5013 strcat(config
->radius_authtypes_s
, ", chap");
5017 strcpy(config
->radius_authtypes_s
, "chap");
5018 if (config
->radius_authtypes
& AUTHPAP
)
5019 strcat(config
->radius_authtypes_s
, ", pap");
5022 if (!config
->radius_dae_port
)
5023 config
->radius_dae_port
= DAEPORT
;
5025 // re-initialise the random number source
5026 initrandom(config
->random_device
);
5029 for (i
= 0; i
< MAXPLUGINS
; i
++)
5031 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5034 if (*config
->plugins
[i
])
5037 add_plugin(config
->plugins
[i
]);
5039 else if (*config
->old_plugins
[i
])
5042 remove_plugin(config
->old_plugins
[i
]);
5047 guest_accounts_num
= 0;
5048 char *p2
= config
->guest_user
;
5051 char *s
= strpbrk(p2
, " \t,");
5055 while (*s
== ' ' || *s
== '\t')
5062 strcpy(guest_users
[guest_accounts_num
], p2
);
5063 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5064 guest_accounts_num
++;
5067 // Rebuild the guest_user array
5068 strcpy(config
->guest_user
, "");
5070 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5072 strcat(config
->guest_user
, guest_users
[ui
]);
5073 if (ui
<guest_accounts_num
-1)
5075 strcat(config
->guest_user
, ",");
5080 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5081 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5082 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5083 if (!*config
->cluster_interface
)
5084 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5086 if (!config
->cluster_hb_interval
)
5087 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5089 if (!config
->cluster_hb_timeout
)
5090 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5092 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5094 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5095 // late, ensure we're sufficiently larger than that
5096 int t
= 4 * config
->cluster_hb_interval
+ 11;
5098 if (config
->cluster_hb_timeout
< t
)
5100 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5101 config
->cluster_hb_timeout
= t
;
5104 // Push timing changes to the slaves immediately if we're the master
5105 if (config
->cluster_iam_master
)
5106 cluster_heartbeat();
5108 interval
= config
->cluster_hb_interval
;
5109 timeout
= config
->cluster_hb_timeout
;
5113 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5116 if ((f
= fopen(config
->pid_file
, "w")))
5118 fprintf(f
, "%d\n", getpid());
5120 config
->wrote_pid
= 1;
5124 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5129 static void read_config_file()
5133 if (!config
->config_file
) return;
5134 if (!(f
= fopen(config
->config_file
, "r")))
5136 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5140 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5142 LOG(3, 0, 0, "Done reading config file\n");
5146 int sessionsetup(sessionidt s
, tunnelidt t
)
5148 // A session now exists, set it up
5154 CSTAT(sessionsetup
);
5156 LOG(3, s
, t
, "Doing session setup for session\n");
5158 // Join a bundle if the MRRU option is accepted
5159 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5161 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5162 if (join_bundle(s
) > 0)
5163 cluster_send_bundle(session
[s
].bundle
);
5166 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5167 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5174 assign_ip_address(s
);
5177 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5178 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5181 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5182 fmtaddr(htonl(session
[s
].ip
), 0));
5186 // Make sure this is right
5187 session
[s
].tunnel
= t
;
5189 // zap old sessions with same IP and/or username
5190 // Don't kill gardened sessions - doing so leads to a DoS
5191 // from someone who doesn't need to know the password
5194 user
= session
[s
].user
;
5195 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5197 if (i
== s
) continue;
5198 if (!session
[s
].opened
) continue;
5199 // Allow duplicate sessions for multilink ones of the same bundle.
5200 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5202 if (ip
== session
[i
].ip
)
5204 sessionkill(i
, "Duplicate IP address");
5208 if (config
->allow_duplicate_users
) continue;
5209 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5213 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5215 if (!strcasecmp(user
, guest_users
[gu
]))
5221 if (found
) continue;
5223 // Drop the new session in case of duplicate sessionss, not the old one.
5224 if (!strcasecmp(user
, session
[i
].user
))
5225 sessionkill(i
, "Duplicate session for users");
5229 // no need to set a route for the same IP address of the bundle
5230 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5234 // Add the route for this session.
5235 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5237 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5238 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5241 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5244 // Static IPs need to be routed if not already
5245 // convered by a Framed-Route. Anything else is part
5246 // of the IP address pool and is already routed, it
5247 // just needs to be added to the IP cache.
5248 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5249 if (session
[s
].ip_pool_index
== -1) // static ip
5251 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5254 cache_ipmap(session
[s
].ip
, s
);
5257 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5258 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5260 // Run the plugin's against this new session.
5262 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5263 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5266 // Allocate TBFs if throttled
5267 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5268 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5270 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5272 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5273 fmtaddr(htonl(session
[s
].ip
), 0),
5274 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5276 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5278 return 1; // RADIUS OK and IP allocated, done...
5282 // This session just got dropped on us by the master or something.
5283 // Make sure our tables up up to date...
5285 int load_session(sessionidt s
, sessiont
*new)
5291 if (new->ip_pool_index
>= MAXIPPOOL
||
5292 new->tunnel
>= MAXTUNNEL
)
5294 LOG(0, s
, 0, "Strange session update received!\n");
5295 // FIXME! What to do here?
5300 // Ok. All sanity checks passed. Now we're committed to
5301 // loading the new session.
5304 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5306 // See if routes/ip cache need updating
5307 if (new->ip
!= session
[s
].ip
)
5310 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5311 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5312 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5320 // remove old routes...
5321 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5323 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5324 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5327 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5333 if (session
[s
].ip_pool_index
== -1) // static IP
5335 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5337 else // It's part of the IP pool, remove it manually.
5338 uncache_ipmap(session
[s
].ip
);
5343 // add new routes...
5344 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5346 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5347 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5350 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5356 // If there's a new one, add it.
5357 if (new->ip_pool_index
== -1)
5359 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5362 cache_ipmap(new->ip
, s
);
5367 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5368 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5371 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5373 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5377 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5379 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5380 new->filter_out
= 0;
5383 if (new->filter_in
!= session
[s
].filter_in
)
5385 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5386 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5389 if (new->filter_out
!= session
[s
].filter_out
)
5391 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5392 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5395 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5396 // for walking the sessions to forward byte counts to the master.
5397 config
->cluster_highest_sessionid
= s
;
5399 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5401 // Do fixups into address pool.
5402 if (new->ip_pool_index
!= -1)
5403 fix_address_pool(s
);
5408 static void initplugins()
5412 loaded_plugins
= ll_init();
5413 // Initialize the plugins to nothing
5414 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5415 plugins
[i
] = ll_init();
5418 static void *open_plugin(char *plugin_name
, int load
)
5420 char path
[256] = "";
5422 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5423 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5424 return dlopen(path
, RTLD_NOW
);
5427 // plugin callback to get a config value
5428 static void *getconfig(char *key
, enum config_typet type
)
5432 for (i
= 0; config_values
[i
].key
; i
++)
5434 if (!strcmp(config_values
[i
].key
, key
))
5436 if (config_values
[i
].type
== type
)
5437 return ((void *) config
) + config_values
[i
].offset
;
5439 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5440 key
, type
, config_values
[i
].type
);
5446 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5450 static int add_plugin(char *plugin_name
)
5452 static struct pluginfuncs funcs
= {
5457 sessiontbysessionidt
,
5458 sessionidtbysessiont
,
5465 cluster_send_session
,
5468 void *p
= open_plugin(plugin_name
, 1);
5469 int (*initfunc
)(struct pluginfuncs
*);
5474 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5478 if (ll_contains(loaded_plugins
, p
))
5481 return 0; // already loaded
5485 int *v
= dlsym(p
, "plugin_api_version");
5486 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5488 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5494 if ((initfunc
= dlsym(p
, "plugin_init")))
5496 if (!initfunc(&funcs
))
5498 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5504 ll_push(loaded_plugins
, p
);
5506 for (i
= 0; i
< max_plugin_functions
; i
++)
5509 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5511 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5512 ll_push(plugins
[i
], x
);
5516 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5520 static void run_plugin_done(void *plugin
)
5522 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5528 static int remove_plugin(char *plugin_name
)
5530 void *p
= open_plugin(plugin_name
, 0);
5536 if (ll_contains(loaded_plugins
, p
))
5539 for (i
= 0; i
< max_plugin_functions
; i
++)
5542 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5543 ll_delete(plugins
[i
], x
);
5546 ll_delete(loaded_plugins
, p
);
5552 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5556 int run_plugins(int plugin_type
, void *data
)
5558 int (*func
)(void *data
);
5560 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5561 return PLUGIN_RET_ERROR
;
5563 ll_reset(plugins
[plugin_type
]);
5564 while ((func
= ll_next(plugins
[plugin_type
])))
5568 if (r
!= PLUGIN_RET_OK
)
5569 return r
; // stop here
5572 return PLUGIN_RET_OK
;
5575 static void plugins_done()
5579 ll_reset(loaded_plugins
);
5580 while ((p
= ll_next(loaded_plugins
)))
5584 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5586 struct nsctl request
;
5587 struct nsctl response
;
5588 int type
= unpack_control(&request
, buf
, len
);
5592 if (log_stream
&& config
->debug
>= 4)
5596 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5597 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5601 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5602 dump_control(&request
, log_stream
);
5608 case NSCTL_REQ_LOAD
:
5609 if (request
.argc
!= 1)
5611 response
.type
= NSCTL_RES_ERR
;
5613 response
.argv
[0] = "name of plugin required";
5615 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5617 response
.type
= NSCTL_RES_ERR
;
5619 response
.argv
[0] = !r
5620 ? "plugin already loaded"
5621 : "error loading plugin";
5625 response
.type
= NSCTL_RES_OK
;
5631 case NSCTL_REQ_UNLOAD
:
5632 if (request
.argc
!= 1)
5634 response
.type
= NSCTL_RES_ERR
;
5636 response
.argv
[0] = "name of plugin required";
5638 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5640 response
.type
= NSCTL_RES_ERR
;
5642 response
.argv
[0] = !r
5643 ? "plugin not loaded"
5644 : "plugin not found";
5648 response
.type
= NSCTL_RES_OK
;
5654 case NSCTL_REQ_HELP
:
5655 response
.type
= NSCTL_RES_OK
;
5658 ll_reset(loaded_plugins
);
5659 while ((p
= ll_next(loaded_plugins
)))
5661 char **help
= dlsym(p
, "plugin_control_help");
5662 while (response
.argc
< 0xff && help
&& *help
)
5663 response
.argv
[response
.argc
++] = *help
++;
5668 case NSCTL_REQ_CONTROL
:
5670 struct param_control param
= {
5671 config
->cluster_iam_master
,
5678 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5680 if (r
== PLUGIN_RET_ERROR
)
5682 response
.type
= NSCTL_RES_ERR
;
5684 response
.argv
[0] = param
.additional
5686 : "error returned by plugin";
5688 else if (r
== PLUGIN_RET_NOTMASTER
)
5690 static char msg
[] = "must be run on master: 000.000.000.000";
5692 response
.type
= NSCTL_RES_ERR
;
5694 if (config
->cluster_master_address
)
5696 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5697 response
.argv
[0] = msg
;
5701 response
.argv
[0] = "must be run on master: none elected";
5704 else if (!(param
.response
& NSCTL_RESPONSE
))
5706 response
.type
= NSCTL_RES_ERR
;
5708 response
.argv
[0] = param
.response
5709 ? "unrecognised response value from plugin"
5710 : "unhandled action";
5714 response
.type
= param
.response
;
5716 if (param
.additional
)
5719 response
.argv
[0] = param
.additional
;
5727 response
.type
= NSCTL_RES_ERR
;
5729 response
.argv
[0] = "error unpacking control packet";
5732 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5735 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5739 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5742 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5743 if (log_stream
&& config
->debug
>= 4)
5745 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5746 dump_control(&response
, log_stream
);
5750 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5751 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5756 static tunnelidt
new_tunnel()
5759 for (i
= 1; i
< MAXTUNNEL
; i
++)
5761 if (tunnel
[i
].state
== TUNNELFREE
)
5763 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5764 if (i
> config
->cluster_highest_tunnelid
)
5765 config
->cluster_highest_tunnelid
= i
;
5769 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5774 // We're becoming the master. Do any required setup..
5776 // This is principally telling all the plugins that we're
5777 // now a master, and telling them about all the sessions
5778 // that are active too..
5780 void become_master(void)
5783 static struct event_data d
[RADIUS_FDS
];
5784 struct epoll_event e
;
5786 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5788 // running a bunch of iptables commands is slow and can cause
5789 // the master to drop tunnels on takeover--kludge around the
5790 // problem by forking for the moment (note: race)
5791 if (!fork_and_close())
5793 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5795 if (!session
[s
].opened
) // Not an in-use session.
5798 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5805 for (i
= 0; i
< RADIUS_FDS
; i
++)
5807 d
[i
].type
= FD_TYPE_RADIUS
;
5811 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5815 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5821 if (CLI_HELP_REQUESTED
)
5822 return CLI_HELP_NO_ARGS
;
5825 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5827 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5830 if (!session
[s
].opened
)
5833 idle
= time_now
- session
[s
].last_data
;
5834 idle
/= 5 ; // In multiples of 5 seconds.
5844 for (i
= 0; i
< 63; ++i
)
5846 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5848 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5849 cli_print(cli
, "%d total sessions open.", count
);
5853 int cmd_show_hist_open(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 d
= time_now
- session
[s
].opened
;
5874 while (d
> 1 && open
< 32)
5884 for (i
= 0; i
< 30; ++i
)
5886 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5889 cli_print(cli
, "%d total sessions open.", count
);
5895 * This unencodes the AVP using the L2TP secret and the previously
5896 * stored random vector. It overwrites the hidden data with the
5897 * unhidden AVP subformat.
5899 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5905 uint16_t m
= htons(type
);
5907 // Compute initial pad
5909 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5910 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5911 MD5_Update(&ctx
, vector
, vec_len
);
5912 MD5_Final(digest
, &ctx
);
5914 // pointer to last decoded 16 octets
5919 // calculate a new pad based on the last decoded block
5920 if (d
>= sizeof(digest
))
5923 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5924 MD5_Update(&ctx
, last
, sizeof(digest
));
5925 MD5_Final(digest
, &ctx
);
5931 *value
++ ^= digest
[d
++];
5936 int find_filter(char const *name
, size_t len
)
5941 for (i
= 0; i
< MAXFILTER
; i
++)
5943 if (!*ip_filters
[i
].name
)
5951 if (strlen(ip_filters
[i
].name
) != len
)
5954 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5961 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5965 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5966 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5967 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5968 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5969 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5975 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5979 case FILTER_FLAG_OP_ANY
:
5980 return (flags
& sflags
) || (~flags
& cflags
);
5982 case FILTER_FLAG_OP_ALL
:
5983 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5985 case FILTER_FLAG_OP_EST
:
5986 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5992 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5994 uint16_t frag_offset
;
5998 uint16_t src_port
= 0;
5999 uint16_t dst_port
= 0;
6001 ip_filter_rulet
*rule
;
6003 if (len
< 20) // up to end of destination address
6006 if ((*buf
>> 4) != 4) // IPv4
6009 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6011 src_ip
= *(in_addr_t
*) (buf
+ 12);
6012 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6014 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6016 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6017 if (len
< l
+ 4) // ports
6020 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6021 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6022 if (proto
== IPPROTO_TCP
)
6024 if (len
< l
+ 14) // flags
6027 flags
= buf
[l
+ 13] & 0x3f;
6031 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6033 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6036 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6037 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6040 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6041 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6046 // layer 4 deny rules are skipped
6047 if (rule
->action
== FILTER_ACTION_DENY
&&
6048 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6056 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6058 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6061 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6064 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6065 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6072 return rule
->action
== FILTER_ACTION_PERMIT
;