3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
11 #include <linux/if_tun.h>
15 #include <net/route.h>
18 #include <netinet/in.h>
19 #include <netinet/ip6.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
29 #include <sys/resource.h>
37 #include <sys/sysinfo.h>
39 #include <linux/netlink.h>
40 #include <linux/rtnetlink.h>
47 #include "constants.h"
59 char * Vendor_name
= "Linux L2TPNS";
60 uint32_t call_serial_number
= 0;
63 configt
*config
= NULL
; // all configuration
64 int nlfd
= -1; // netlink socket
65 int tunfd
= -1; // tun interface file handle. (network device)
66 int udpfd
[MAX_UDPFD
+ 1] = INIT_TABUDPFD
; // array UDP file handle + 1 for lac udp
67 int udplacfd
= -1; // UDP LAC file handle
68 int controlfd
= -1; // Control signal handle
69 int clifd
= -1; // Socket listening for CLI connections.
70 int daefd
= -1; // Socket listening for DAE connections.
71 int snoopfd
= -1; // UDP file handle for sending out intercept data
72 int *radfds
= NULL
; // RADIUS requests file handles
73 int rand_fd
= -1; // Random data source
74 int cluster_sockfd
= -1; // Intra-cluster communications socket.
75 int epollfd
= -1; // event polling
76 time_t basetime
= 0; // base clock
77 char hostname
[MAXHOSTNAME
] = ""; // us.
78 int tunidx
; // ifr_ifindex of tun device
79 int nlseqnum
= 0; // netlink sequence number
80 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
81 static int syslog_log
= 0; // are we logging to syslog
82 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
83 uint32_t last_id
= 0; // Unique ID for radius accounting
85 char guest_users
[10][32]; // Array of guest users
86 int guest_accounts_num
= 0; // Number of guest users
88 // calculated from config->l2tp_mtu
89 uint16_t MRU
= 0; // PPP MRU
90 uint16_t MSS
= 0; // TCP MSS
92 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
93 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
95 union iphash ip_hash
[256]; // Mapping from IP address to session structures.
99 struct ipv6radix
*branch
;
100 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
103 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
104 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
107 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
108 time_t time_now
= 0; // Current time in seconds since epoch.
109 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
110 static char time_now_string
[64] = {0}; // Current time as a string.
111 static int time_changed
= 0; // time_now changed
112 char main_quit
= 0; // True if we're in the process of exiting.
113 static char main_reload
= 0; // Re-load pending
114 linked_list
*loaded_plugins
;
115 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
117 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
118 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
120 config_descriptt config_values
[] = {
121 CONFIG("debug", debug
, INT
),
122 CONFIG("log_file", log_filename
, STRING
),
123 CONFIG("pid_file", pid_file
, STRING
),
124 CONFIG("random_device", random_device
, STRING
),
125 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
126 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
127 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
128 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
129 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
130 CONFIG("primary_dns", default_dns1
, IPv4
),
131 CONFIG("secondary_dns", default_dns2
, IPv4
),
132 CONFIG("primary_radius", radiusserver
[0], IPv4
),
133 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
134 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
135 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
136 CONFIG("radius_accounting", radius_accounting
, BOOL
),
137 CONFIG("radius_interim", radius_interim
, INT
),
138 CONFIG("radius_secret", radiussecret
, STRING
),
139 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
140 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
141 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
142 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
143 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
144 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
145 CONFIG("guest_account", guest_user
, STRING
),
146 CONFIG("bind_address", bind_address
, IPv4
),
147 CONFIG("peer_address", peer_address
, IPv4
),
148 CONFIG("send_garp", send_garp
, BOOL
),
149 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
150 CONFIG("throttle_buckets", num_tbfs
, INT
),
151 CONFIG("accounting_dir", accounting_dir
, STRING
),
152 CONFIG("dump_speed", dump_speed
, BOOL
),
153 CONFIG("multi_read_count", multi_read_count
, INT
),
154 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
155 CONFIG("lock_pages", lock_pages
, BOOL
),
156 CONFIG("icmp_rate", icmp_rate
, INT
),
157 CONFIG("packet_limit", max_packets
, INT
),
158 CONFIG("cluster_address", cluster_address
, IPv4
),
159 CONFIG("cluster_interface", cluster_interface
, STRING
),
160 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
161 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
162 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
163 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
164 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
165 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
166 CONFIG("hostname", hostname
, STRING
),
168 CONFIG("nexthop_address", nexthop_address
, IPv4
),
169 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
171 CONFIG("echo_timeout", echo_timeout
, INT
),
172 CONFIG("idle_echo_timeout", idle_echo_timeout
, INT
),
173 CONFIG("iftun_address", iftun_address
, IPv4
),
174 CONFIG("tundevicename", tundevicename
, STRING
),
175 CONFIG("disable_lac_func", disable_lac_func
, BOOL
),
176 CONFIG("auth_tunnel_change_addr_src", auth_tunnel_change_addr_src
, BOOL
),
177 CONFIG("bind_address_remotelns", bind_address_remotelns
, IPv4
),
178 CONFIG("bind_portremotelns", bind_portremotelns
, SHORT
),
179 CONFIG("pppoe_if_to_bind", pppoe_if_to_bind
, STRING
),
180 CONFIG("pppoe_service_name", pppoe_service_name
, STRING
),
181 CONFIG("pppoe_ac_name", pppoe_ac_name
, STRING
),
182 CONFIG("disable_sending_hello", disable_sending_hello
, BOOL
),
183 CONFIG("disable_no_spoof", disable_no_spoof
, BOOL
),
184 CONFIG("bind_multi_address", bind_multi_address
, STRING
),
185 CONFIG("grp_txrate_average_time", grp_txrate_average_time
, INT
),
189 static char *plugin_functions
[] = {
194 "plugin_new_session",
195 "plugin_kill_session",
197 "plugin_radius_response",
198 "plugin_radius_reset",
199 "plugin_radius_account",
200 "plugin_become_master",
201 "plugin_new_session_master",
204 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
206 // Counters for shutdown sessions
207 static sessiont shut_acct
[8192];
208 static sessionidt shut_acct_n
= 0;
210 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
211 bundlet
*bundle
= NULL
; // Array of bundle structures.
212 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
213 sessiont
*session
= NULL
; // Array of session structures.
214 groupsesst
*grpsession
= NULL
; // Array of groupsesst structures.
215 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
216 radiust
*radius
= NULL
; // Array of radius structures.
217 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
218 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
219 static controlt
*controlfree
= 0;
220 struct Tstats
*_statistics
= NULL
;
222 struct Tringbuffer
*ringbuffer
= NULL
;
225 static void uncache_ipmap(in_addr_t ip
);
226 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
227 static void free_ip_address(sessionidt s
);
228 static void dump_acct_info(int all
);
229 static void sighup_handler(int sig
);
230 static void shutdown_handler(int sig
);
231 static void sigchild_handler(int sig
);
232 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
233 static void update_config(void);
234 static void read_config_file(void);
235 static void initplugins(void);
236 static int add_plugin(char *plugin_name
);
237 static int remove_plugin(char *plugin_name
);
238 static void plugins_done(void);
239 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
240 static tunnelidt
new_tunnel(void);
241 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
242 static void bundleclear(bundleidt b
);
244 // return internal time (10ths since process startup), set f if given
245 // as a side-effect sets time_now, and time_changed
246 static clockt
now(double *f
)
250 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
251 if (t
.tv_sec
!= time_now
)
258 // Time in milliseconds
259 // TODO FOR MLPPP DEV
260 //time_now_ms = (t.tv_sec * 1000) + (t.tv_usec/1000);
262 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
265 // work out a retry time based on try number
266 // This is a straight bounded exponential backoff.
267 // Maximum re-try time is 32 seconds. (2^5).
268 clockt
backoff(uint8_t try)
270 if (try > 5) try = 5; // max backoff
271 return now(NULL
) + 10 * (1 << try);
276 // Log a debug message. Typically called via the LOG macro
278 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
280 static char message
[65536] = {0};
286 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
287 ringbuffer
->tail
= 0;
288 if (ringbuffer
->tail
== ringbuffer
->head
)
289 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
290 ringbuffer
->head
= 0;
292 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
293 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
294 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
295 va_start(ap
, format
);
296 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, MAX_LOG_LENGTH
, format
, ap
);
301 if (config
->debug
< level
) return;
303 va_start(ap
, format
);
304 vsnprintf(message
, sizeof(message
), format
, ap
);
307 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
309 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
314 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
317 const uint8_t *d
= data
;
319 if (config
->debug
< level
) return;
321 // No support for _log_hex to syslog
324 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
325 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
327 for (i
= 0; i
< maxsize
; )
329 fprintf(log_stream
, "%4X: ", i
);
330 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
332 fprintf(log_stream
, "%02X ", d
[j
]);
334 fputs(": ", log_stream
);
337 for (; j
< i
+ 16; j
++)
339 fputs(" ", log_stream
);
341 fputs(": ", log_stream
);
344 fputs(" ", log_stream
);
345 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
347 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
348 fputc(d
[j
], log_stream
);
350 fputc('.', log_stream
);
353 fputs(" ", log_stream
);
357 fputs("\n", log_stream
);
361 setbuf(log_stream
, NULL
);
365 // update a counter, accumulating 2^32 wraps
366 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
368 uint32_t new = *counter
+ delta
;
375 // initialise the random generator
376 static void initrandom(char *source
)
378 static char path
[sizeof(config
->random_device
)] = "*undefined*";
380 // reinitialise only if we are forced to do so or if the config has changed
381 if (source
&& !strncmp(path
, source
, sizeof(path
)))
384 // close previous source, if any
393 snprintf(path
, sizeof(path
), "%s", source
);
397 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
399 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
400 path
, strerror(errno
));
405 // fill buffer with random data
406 void random_data(uint8_t *buf
, int len
)
413 n
= read(rand_fd
, buf
, len
);
414 if (n
>= len
) return;
419 LOG(0, 0, 0, "Error reading from random source: %s\n",
422 // fall back to rand()
430 // append missing data
432 // not using the low order bits from the prng stream
433 buf
[n
++] = (rand() >> 4) & 0xff;
438 // This adds it to the routing table, advertises it
439 // via BGP if enabled, and stuffs it into the
440 // 'sessionbyip' cache.
442 // 'ip' must be in _host_ order.
444 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
454 if (!prefixlen
) prefixlen
= 32;
456 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
458 memset(&req
, 0, sizeof(req
));
462 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
463 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
467 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
468 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
471 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
473 req
.rt
.rtm_family
= AF_INET
;
474 req
.rt
.rtm_dst_len
= prefixlen
;
475 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
476 req
.rt
.rtm_protocol
= 42;
477 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
478 req
.rt
.rtm_type
= RTN_UNICAST
;
480 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
482 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
486 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
489 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
490 fmtaddr(htonl(ip
), 0), prefixlen
,
491 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
493 if (netlink_send(&req
.nh
) < 0)
494 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
498 bgp_add_route(htonl(ip
), prefixlen
);
500 bgp_del_route(htonl(ip
), prefixlen
);
503 // Add/Remove the IPs to the 'sessionbyip' cache.
504 // Note that we add the zero address in the case of
505 // a network route. Roll on CIDR.
507 // Note that 's == 0' implies this is the address pool.
508 // We still cache it here, because it will pre-fill
509 // the malloc'ed tree.
513 if (!add
) // Are we deleting a route?
514 s
= 0; // Caching the session as '0' is the same as uncaching.
516 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
521 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
529 char ipv6addr
[INET6_ADDRSTRLEN
];
531 if (!config
->ipv6_prefix
.s6_addr
[0])
533 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
537 memset(&req
, 0, sizeof(req
));
541 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
542 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
546 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
547 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
550 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
552 req
.rt
.rtm_family
= AF_INET6
;
553 req
.rt
.rtm_dst_len
= prefixlen
;
554 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
555 req
.rt
.rtm_protocol
= 42;
556 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
557 req
.rt
.rtm_type
= RTN_UNICAST
;
559 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
560 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
562 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
564 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
566 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
569 if (netlink_send(&req
.nh
) < 0)
570 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
574 bgp_add_route6(ip
, prefixlen
);
576 bgp_del_route6(ip
, prefixlen
);
581 if (!add
) // Are we deleting a route?
582 s
= 0; // Caching the session as '0' is the same as uncaching.
584 cache_ipv6map(ip
, prefixlen
, s
);
591 // Set up netlink socket
592 static void initnetlink(void)
594 struct sockaddr_nl nladdr
;
596 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
599 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
603 memset(&nladdr
, 0, sizeof(nladdr
));
604 nladdr
.nl_family
= AF_NETLINK
;
605 nladdr
.nl_pid
= getpid();
607 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
609 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
614 ssize_t
netlink_send(struct nlmsghdr
*nh
)
616 struct sockaddr_nl nladdr
;
620 nh
->nlmsg_pid
= getpid();
621 nh
->nlmsg_seq
= ++nlseqnum
;
623 // set kernel address
624 memset(&nladdr
, 0, sizeof(nladdr
));
625 nladdr
.nl_family
= AF_NETLINK
;
627 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
628 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
630 return sendmsg(nlfd
, &msg
, 0);
633 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
635 struct sockaddr_nl nladdr
;
639 // set kernel address
640 memset(&nladdr
, 0, sizeof(nladdr
));
641 nladdr
.nl_family
= AF_NETLINK
;
643 iov
= (struct iovec
){ buf
, len
};
644 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
646 return recvmsg(nlfd
, &msg
, 0);
649 /* adapted from iproute2 */
650 void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
652 int len
= RTA_LENGTH(alen
);
655 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
656 rta
->rta_type
= type
;
658 memcpy(RTA_DATA(rta
), data
, alen
);
659 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
662 // messages corresponding to different phases seq number
663 static char *tun_nl_phase_msg
[] = {
665 "getting tun interface index",
666 "setting tun interface parameters",
667 "setting tun IPv4 address",
668 "setting tun LL IPv6 address",
669 "setting tun global IPv6 address",
673 // Set up TUN interface
674 static void inittun(void)
678 memset(&ifr
, 0, sizeof(ifr
));
679 ifr
.ifr_flags
= IFF_TUN
;
681 tunfd
= open(TUNDEVICE
, O_RDWR
);
684 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
688 int flags
= fcntl(tunfd
, F_GETFL
, 0);
689 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
692 if (*config
->tundevicename
)
693 strncpy(ifr
.ifr_name
, config
->tundevicename
, IFNAMSIZ
);
695 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
697 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
700 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevicename
) - 1);
701 strncpy(config
->tundevicename
, ifr
.ifr_name
, sizeof(config
->tundevicename
));
703 tunidx
= if_nametoindex(config
->tundevicename
);
706 LOG(0, 0, 0, "Can't get tun interface index\n");
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_NEWLINK
;
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
.ifi_family
= AF_UNSPEC
;
730 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
731 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
732 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
734 /* Bump up the qlen to deal with bursts from the network */
736 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
737 /* set MTU to modem MRU */
739 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
741 if (netlink_send(&req
.nh
) < 0)
744 memset(&req
, 0, sizeof(req
));
746 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
747 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
748 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
750 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
751 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
752 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
753 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
755 if (config
->nbmultiaddress
> 1)
758 for (i
= 0; i
< config
->nbmultiaddress
; i
++)
760 ip
= config
->iftun_n_address
[i
];
761 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
762 if (netlink_send(&req
.nh
) < 0)
768 if (config
->iftun_address
)
769 ip
= config
->iftun_address
;
771 ip
= 0x01010101; // 1.1.1.1
772 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
774 if (netlink_send(&req
.nh
) < 0)
780 // Only setup IPv6 on the tun device if we have a configured prefix
781 if (config
->ipv6_prefix
.s6_addr
[0]) {
784 memset(&req
, 0, sizeof(req
));
786 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
787 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
788 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
790 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
791 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
792 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
793 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
795 // Link local address is FE80::1
796 memset(&ip6
, 0, sizeof(ip6
));
797 ip6
.s6_addr
[0] = 0xFE;
798 ip6
.s6_addr
[1] = 0x80;
800 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
802 if (netlink_send(&req
.nh
) < 0)
805 memset(&req
, 0, sizeof(req
));
807 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
808 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
809 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
811 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
812 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
813 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
814 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
816 // Global address is prefix::1
817 ip6
= config
->ipv6_prefix
;
819 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
821 if (netlink_send(&req
.nh
) < 0)
825 memset(&req
, 0, sizeof(req
));
827 req
.nh
.nlmsg_type
= NLMSG_DONE
;
828 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
830 if (netlink_send(&req
.nh
) < 0)
833 // if we get an error for seqnum < min_initok_nlseqnum,
834 // we must exit as initialization went wrong
835 if (config
->ipv6_prefix
.s6_addr
[0])
836 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
838 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
844 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
848 // set up LAC UDP ports
849 static void initlacudp(void)
852 struct sockaddr_in addr
;
854 // Tunnel to Remote LNS
855 memset(&addr
, 0, sizeof(addr
));
856 addr
.sin_family
= AF_INET
;
857 addr
.sin_port
= htons(config
->bind_portremotelns
);
858 addr
.sin_addr
.s_addr
= config
->bind_address_remotelns
;
859 udplacfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
860 setsockopt(udplacfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
862 int flags
= fcntl(udplacfd
, F_GETFL
, 0);
863 fcntl(udplacfd
, F_SETFL
, flags
| O_NONBLOCK
);
865 if (bind(udplacfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
867 LOG(0, 0, 0, "Error in UDP REMOTE LNS bind: %s\n", strerror(errno
));
872 // set up control ports
873 static void initcontrol(void)
876 struct sockaddr_in addr
;
879 memset(&addr
, 0, sizeof(addr
));
880 addr
.sin_family
= AF_INET
;
881 addr
.sin_port
= htons(NSCTL_PORT
);
882 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
883 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
884 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
885 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
887 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
892 // set up Dynamic Authorization Extensions to RADIUS port
893 static void initdae(void)
896 struct sockaddr_in addr
;
898 // Dynamic Authorization Extensions to RADIUS
899 memset(&addr
, 0, sizeof(addr
));
900 addr
.sin_family
= AF_INET
;
901 addr
.sin_port
= htons(config
->radius_dae_port
);
902 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
903 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
904 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
905 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
907 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
913 static void initudp(int * pudpfd
, in_addr_t ip_bind
)
916 struct sockaddr_in addr
;
919 memset(&addr
, 0, sizeof(addr
));
920 addr
.sin_family
= AF_INET
;
921 addr
.sin_port
= htons(L2TPPORT
);
922 addr
.sin_addr
.s_addr
= ip_bind
;
923 (*pudpfd
) = socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
924 setsockopt((*pudpfd
), SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
926 int flags
= fcntl((*pudpfd
), F_GETFL
, 0);
927 fcntl((*pudpfd
), F_SETFL
, flags
| O_NONBLOCK
);
929 if (bind((*pudpfd
), (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
931 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
937 // Find session by IP, < 1 for not found
939 // Confusingly enough, this 'ip' must be
940 // in _network_ order. This being the common
941 // case when looking it up from IP packet headers.
943 // We actually use this cache for two things.
944 // #1. For used IP addresses, this maps to the
945 // session ID that it's used by.
946 // #2. For un-used IP addresses, this maps to the
947 // index into the pool table that contains that
951 static sessionidt
lookup_ipmap(in_addr_t ip
)
953 uint8_t *a
= (uint8_t *) &ip
;
954 union iphash
*h
= ip_hash
;
956 if (!(h
= h
[*a
++].idx
)) return 0;
957 if (!(h
= h
[*a
++].idx
)) return 0;
958 if (!(h
= h
[*a
++].idx
)) return 0;
963 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
965 struct ipv6radix
*curnode
;
968 char ipv6addr
[INET6_ADDRSTRLEN
];
970 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
974 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
976 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
981 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
982 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
989 sessionidt
sessionbyip(in_addr_t ip
)
991 sessionidt s
= lookup_ipmap(ip
);
994 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1000 sessionidt
sessionbyipv6(struct in6_addr ip
)
1003 CSTAT(sessionbyipv6
);
1005 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
1006 (ip
.s6_addr
[0] == 0xFE &&
1007 ip
.s6_addr
[1] == 0x80 &&
1008 ip
.s6_addr16
[1] == 0 &&
1009 ip
.s6_addr16
[2] == 0 &&
1010 ip
.s6_addr16
[3] == 0)) {
1011 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
1013 s
= lookup_ipv6map(ip
);
1016 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1023 // Take an IP address in HOST byte order and
1024 // add it to the sessionid by IP cache.
1026 // (It's actually cached in network order)
1028 void cache_ipmap(in_addr_t ip
, sessionidt s
)
1030 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
1031 uint8_t *a
= (uint8_t *) &nip
;
1032 union iphash
*h
= ip_hash
;
1035 for (i
= 0; i
< 3; i
++)
1037 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1046 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1049 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1050 // else a map to an ip pool index.
1053 static void uncache_ipmap(in_addr_t ip
)
1055 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1058 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1062 struct ipv6radix
*curnode
;
1063 char ipv6addr
[INET6_ADDRSTRLEN
];
1065 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
1067 bytes
= prefixlen
>> 3;
1070 if (curnode
->branch
== NULL
)
1072 if (!(curnode
->branch
= calloc(256,
1073 sizeof (struct ipv6radix
))))
1076 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1083 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1084 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1088 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1089 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1095 // CLI list to dump current ipcache.
1097 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1099 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1103 if (CLI_HELP_REQUESTED
)
1104 return CLI_HELP_NO_ARGS
;
1106 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1108 for (i
= 0; i
< 256; ++i
)
1114 for (j
= 0; j
< 256; ++j
)
1120 for (k
= 0; k
< 256; ++k
)
1126 for (l
= 0; l
< 256; ++l
)
1131 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1137 cli_print(cli
, "%d entries in cache", count
);
1142 // Find session by username, 0 for not found
1143 // walled garden users aren't authenticated, so the username is
1144 // reasonably useless. Ignore them to avoid incorrect actions
1146 // This is VERY inefficent. Don't call it often. :)
1148 sessionidt
sessionbyuser(char *username
)
1151 CSTAT(sessionbyuser
);
1153 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1155 if (!session
[s
].opened
)
1158 if (session
[s
].walled_garden
)
1159 continue; // Skip walled garden users.
1161 if (!strncmp(session
[s
].user
, username
, 128))
1165 return 0; // Not found.
1168 void send_garp(in_addr_t ip
)
1174 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1177 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1180 memset(&ifr
, 0, sizeof(ifr
));
1181 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1182 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1184 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1188 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1189 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1191 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1196 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1199 static sessiont
*sessiontbysessionidt(sessionidt s
)
1201 if (!s
|| s
>= MAXSESSION
) return NULL
;
1205 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1207 sessionidt val
= s
-session
;
1208 if (s
< session
|| val
>= MAXSESSION
) return 0;
1212 // actually send a control message for a specific tunnel
1213 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1215 struct sockaddr_in addr
;
1221 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1222 STAT(tunnel_tx_errors
);
1226 if (t
== TUNNEL_ID_PPPOE
)
1228 pppoe_sess_send(buf
, l
, t
);
1234 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1235 STAT(tunnel_tx_errors
);
1239 memset(&addr
, 0, sizeof(addr
));
1240 addr
.sin_family
= AF_INET
;
1241 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1242 addr
.sin_port
= htons(tunnel
[t
].port
);
1244 // sequence expected, if sequence in message
1245 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1247 // If this is a control message, deal with retries
1250 tunnel
[t
].last
= time_now
; // control message sent
1251 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1254 STAT(tunnel_retries
);
1255 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1259 if (sendto(udpfd
[tunnel
[t
].indexudp
], buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1261 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1262 strerror(errno
), udpfd
[tunnel
[t
].indexudp
], buf
, l
, inet_ntoa(addr
.sin_addr
));
1263 STAT(tunnel_tx_errors
);
1267 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1268 STAT(tunnel_tx_packets
);
1269 INC_STAT(tunnel_tx_bytes
, l
);
1273 // Tiny helper function to write data to
1274 // the 'tun' device.
1276 int tun_write(uint8_t * data
, int size
)
1278 return write(tunfd
, data
, size
);
1281 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1282 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1284 int d
= (tcp
[12] >> 4) * 4;
1291 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1294 if (tcp
+ d
> buf
+ len
) // short?
1302 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1305 if (mss
+ 2 > data
) return; // short?
1309 if (*opts
== 0) return; // end of options
1310 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1313 opts
+= opts
[1]; // skip over option
1316 if (!mss
) return; // not found
1317 orig
= ntohs(*(uint16_t *) mss
);
1319 if (orig
<= MSS
) return; // mss OK
1321 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1322 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1323 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1324 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1327 *(int16_t *) mss
= htons(MSS
);
1329 // adjust checksum (see rfc1141)
1330 sum
= orig
+ (~MSS
& 0xffff);
1331 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1332 sum
= (sum
& 0xffff) + (sum
>> 16);
1333 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1336 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1340 // Skip the four extra bytes
1352 proto
= ntohs(*(uint16_t *) p
);
1360 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1361 return; // closing session, PPP not processed
1363 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1364 processipin(s
, t
, p
, l
);
1366 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1370 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1371 return; // closing session, PPP not processed
1374 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1375 processipv6in(s
, t
, p
, l
);
1377 else if (proto
== PPPIPCP
)
1379 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1380 processipcp(s
, t
, p
, l
);
1382 else if (proto
== PPPCCP
)
1384 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1385 processccp(s
, t
, p
, l
);
1389 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1393 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1395 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1396 sp
->cout_delta
+= len
;
1398 sp
->last_data
= time_now
;
1400 sess_local
[s
].cout
+= len
; // To send to master..
1401 sess_local
[s
].pout
++;
1404 // process outgoing (to tunnel) IP
1406 // (i.e. this routine writes to data[-8]).
1407 void processipout(uint8_t *buf
, int len
)
1415 uint8_t *data
= buf
; // Keep a copy of the originals.
1418 uint8_t fragbuf
[MAXETHER
+ 20];
1420 CSTAT(processipout
);
1422 if (len
< MIN_IP_SIZE
)
1424 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1425 STAT(tun_rx_errors
);
1428 if (len
>= MAXETHER
)
1430 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1431 STAT(tun_rx_errors
);
1435 // Skip the tun header
1439 // Got an IP header now
1440 if (*(uint8_t *)(buf
) >> 4 != 4)
1442 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1446 ip
= *(uint32_t *)(buf
+ 16);
1447 if ((g
= grp_groupbyip(ip
)))
1449 s
= grp_getnextsession(g
, ip
);
1452 // Is this a packet for a session that doesn't exist?
1453 static int rate
= 0; // Number of ICMP packets we've sent this second.
1454 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1456 if (last
!= time_now
)
1462 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1464 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1465 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1466 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1471 else if (!(s
= sessionbyip(ip
)))
1473 // Is this a packet for a session that doesn't exist?
1474 static int rate
= 0; // Number of ICMP packets we've sent this second.
1475 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1477 if (last
!= time_now
)
1483 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1485 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1486 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1487 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1492 t
= session
[s
].tunnel
;
1493 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1495 LOG(3, s
, t
, "Packet size more than session MRU\n");
1501 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1502 if (config
->max_packets
> 0)
1504 if (sess_local
[s
].last_packet_out
== TIME
)
1506 int max
= config
->max_packets
;
1508 // All packets for throttled sessions are handled by the
1509 // master, so further limit by using the throttle rate.
1510 // A bit of a kludge, since throttle rate is in kbps,
1511 // but should still be generous given our average DSL
1512 // packet size is 200 bytes: a limit of 28kbps equates
1513 // to around 180 packets per second.
1514 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1515 max
= sp
->throttle_out
;
1517 if (++sess_local
[s
].packets_out
> max
)
1519 sess_local
[s
].packets_dropped
++;
1525 if (sess_local
[s
].packets_dropped
)
1527 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1528 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1529 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1530 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1534 sess_local
[s
].last_packet_out
= TIME
;
1535 sess_local
[s
].packets_out
= 1;
1536 sess_local
[s
].packets_dropped
= 0;
1540 // run access-list if any
1541 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1544 // adjust MSS on SYN and SYN,ACK packets with options
1545 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1547 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1548 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1549 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1554 // Are we throttling this session?
1555 if (config
->cluster_iam_master
)
1556 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1558 master_throttle_packet(sp
->tbf_out
, data
, size
);
1562 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1564 // We are walled-gardening this
1565 master_garden_packet(s
, data
, size
);
1569 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1572 if (!config
->cluster_iam_master
)
1574 // The MPPP packets must be managed by the Master.
1575 master_forward_mppp_packet(s
, data
, size
);
1579 // Add on L2TP header
1580 sessionidt members
[MAXBUNDLESES
];
1581 bundleidt bid
= session
[s
].bundle
;
1582 bundlet
*b
= &bundle
[bid
];
1583 uint32_t num_of_links
, nb_opened
;
1586 num_of_links
= b
->num_of_links
;
1588 for (i
= 0;i
< num_of_links
;i
++)
1591 if (session
[s
].ppp
.lcp
== Opened
)
1593 members
[nb_opened
] = s
;
1600 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1604 num_of_links
= nb_opened
;
1605 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1606 s
= members
[b
->current_ses
];
1607 t
= session
[s
].tunnel
;
1609 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1611 if (num_of_links
> 1)
1613 if(len
> MINFRAGLEN
)
1615 //for rotate traffic among the member links
1616 uint32_t divisor
= num_of_links
;
1618 divisor
= divisor
/2 + (divisor
& 1);
1620 // Partition the packet to "num_of_links" fragments
1621 uint32_t fraglen
= len
/ divisor
;
1622 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1623 uint32_t remain
= len
;
1625 // send the first packet
1626 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1628 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1631 update_session_out_stat(s
, sp
, fraglen
);
1634 while (remain
> last_fraglen
)
1636 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1637 s
= members
[b
->current_ses
];
1638 t
= session
[s
].tunnel
;
1640 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1641 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1643 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1644 update_session_out_stat(s
, sp
, fraglen
);
1647 // send the last fragment
1648 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1649 s
= members
[b
->current_ses
];
1650 t
= session
[s
].tunnel
;
1652 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1653 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1655 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1656 update_session_out_stat(s
, sp
, remain
);
1657 if (remain
!= last_fraglen
)
1658 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1662 // Send it as one frame
1663 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1665 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1666 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1667 update_session_out_stat(s
, sp
, len
);
1672 // Send it as one frame (NO MPPP Frame)
1673 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1674 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1675 update_session_out_stat(s
, sp
, len
);
1680 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1681 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1682 update_session_out_stat(s
, sp
, len
);
1685 // Snooping this session, send it to intercept box
1686 if (sp
->snoop_ip
&& sp
->snoop_port
)
1687 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1692 // process outgoing (to tunnel) IPv6
1694 static void processipv6out(uint8_t * buf
, int len
)
1700 struct in6_addr ip6
;
1702 uint8_t *data
= buf
; // Keep a copy of the originals.
1705 uint8_t b
[MAXETHER
+ 20];
1707 CSTAT(processipv6out
);
1709 if (len
< MIN_IP_SIZE
)
1711 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1712 STAT(tunnel_tx_errors
);
1715 if (len
>= MAXETHER
)
1717 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1718 STAT(tunnel_tx_errors
);
1722 // Skip the tun header
1726 // Got an IP header now
1727 if (*(uint8_t *)(buf
) >> 4 != 6)
1729 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1733 ip6
= *(struct in6_addr
*)(buf
+24);
1734 s
= sessionbyipv6(ip6
);
1738 ip
= *(uint32_t *)(buf
+ 32);
1739 s
= sessionbyip(ip
);
1744 // Is this a packet for a session that doesn't exist?
1745 static int rate
= 0; // Number of ICMP packets we've sent this second.
1746 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1748 if (last
!= time_now
)
1754 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1756 // FIXME: Should send icmp6 host unreachable
1760 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1762 bundleidt bid
= session
[s
].bundle
;
1763 bundlet
*b
= &bundle
[bid
];
1765 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1766 s
= b
->members
[b
->current_ses
];
1767 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1769 t
= session
[s
].tunnel
;
1771 sp
->last_data
= time_now
;
1773 // FIXME: add DoS prevention/filters?
1777 // Are we throttling this session?
1778 if (config
->cluster_iam_master
)
1779 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1781 master_throttle_packet(sp
->tbf_out
, data
, size
);
1784 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1786 // We are walled-gardening this
1787 master_garden_packet(s
, data
, size
);
1791 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1793 // Add on L2TP header
1795 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1797 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1800 // Snooping this session, send it to intercept box
1801 if (sp
->snoop_ip
&& sp
->snoop_port
)
1802 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1804 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1805 sp
->cout_delta
+= len
;
1809 sess_local
[s
].cout
+= len
; // To send to master..
1810 sess_local
[s
].pout
++;
1814 // Helper routine for the TBF filters.
1815 // Used to send queued data in to the user!
1817 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1822 uint8_t b
[MAXETHER
+ 20];
1824 if (len
< 0 || len
> MAXETHER
)
1826 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1830 // Skip the tun header
1837 t
= session
[s
].tunnel
;
1840 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1842 // Add on L2TP header
1844 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1846 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1849 // Snooping this session.
1850 if (sp
->snoop_ip
&& sp
->snoop_port
)
1851 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1853 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1854 sp
->cout_delta
+= len
;
1858 sess_local
[s
].cout
+= len
; // To send to master..
1859 sess_local
[s
].pout
++;
1862 // add an AVP (16 bit)
1863 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1865 uint16_t l
= (m
? 0x8008 : 0x0008);
1866 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1867 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1868 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1869 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1873 // add an AVP (32 bit)
1874 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1876 uint16_t l
= (m
? 0x800A : 0x000A);
1877 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1878 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1879 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1880 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1884 // add an AVP (string)
1885 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1887 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1888 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1889 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1890 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1891 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1892 c
->length
+= 6 + strlen(val
);
1896 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1898 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1899 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1900 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1901 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1902 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1903 c
->length
+= 6 + len
;
1906 // new control connection
1907 static controlt
*controlnew(uint16_t mtype
)
1911 c
= malloc(sizeof(controlt
));
1915 controlfree
= c
->next
;
1919 c
->buf
[0] = 0xC8; // flags
1920 c
->buf
[1] = 0x02; // ver
1922 control16(c
, 0, mtype
, 1);
1926 // send zero block if nothing is waiting
1928 static void controlnull(tunnelidt t
)
1931 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1934 buf
[0] = htons(0xC802); // flags/ver
1935 buf
[1] = htons(12); // length
1936 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1937 buf
[3] = htons(0); // session
1938 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1939 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1940 tunnelsend((uint8_t *)buf
, 12, t
);
1943 // add a control message to a tunnel, and send if within window
1944 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1946 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1947 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1948 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1949 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1950 tunnel
[t
].ns
++; // advance sequence
1951 // link in message in to queue
1952 if (tunnel
[t
].controlc
)
1953 tunnel
[t
].controle
->next
= c
;
1955 tunnel
[t
].controls
= c
;
1957 tunnel
[t
].controle
= c
;
1958 tunnel
[t
].controlc
++;
1960 // send now if space in window
1961 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1963 tunnel
[t
].try = 0; // first send
1964 tunnelsend(c
->buf
, c
->length
, t
);
1969 // Throttle or Unthrottle a session
1971 // Throttle the data from/to through a session to no more than
1972 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1975 // If either value is -1, the current value is retained for that
1978 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1980 if (!session
[s
].opened
)
1981 return; // No-one home.
1983 if (!*session
[s
].user
)
1984 return; // User not logged in
1988 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1989 if (session
[s
].tbf_in
)
1990 free_tbf(session
[s
].tbf_in
);
1993 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1995 session
[s
].tbf_in
= 0;
1997 session
[s
].throttle_in
= rate_in
;
2002 int bytes
= rate_out
* 1024 / 8;
2003 if (session
[s
].tbf_out
)
2004 free_tbf(session
[s
].tbf_out
);
2007 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
2009 session
[s
].tbf_out
= 0;
2011 session
[s
].throttle_out
= rate_out
;
2015 // add/remove filters from session (-1 = no change)
2016 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
2018 if (!session
[s
].opened
)
2019 return; // No-one home.
2021 if (!*session
[s
].user
)
2022 return; // User not logged in
2025 if (filter_in
> MAXFILTER
) filter_in
= -1;
2026 if (filter_out
> MAXFILTER
) filter_out
= -1;
2027 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
2028 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
2032 if (session
[s
].filter_in
)
2033 ip_filters
[session
[s
].filter_in
- 1].used
--;
2036 ip_filters
[filter_in
- 1].used
++;
2038 session
[s
].filter_in
= filter_in
;
2041 if (filter_out
>= 0)
2043 if (session
[s
].filter_out
)
2044 ip_filters
[session
[s
].filter_out
- 1].used
--;
2047 ip_filters
[filter_out
- 1].used
++;
2049 session
[s
].filter_out
= filter_out
;
2053 // start tidy shutdown of session
2054 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
2056 int walled_garden
= session
[s
].walled_garden
;
2057 bundleidt b
= session
[s
].bundle
;
2058 //delete routes only for last session in bundle (in case of MPPP)
2059 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
2061 CSTAT(sessionshutdown
);
2063 if (!session
[s
].opened
)
2065 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2066 return; // not a live session
2069 if (!session
[s
].die
)
2071 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2072 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2073 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2076 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2078 // RADIUS Stop message
2079 uint16_t r
= radiusnew(s
);
2082 // stop, if not already trying
2083 if (radius
[r
].state
!= RADIUSSTOP
)
2085 radius
[r
].term_cause
= term_cause
;
2086 radius
[r
].term_msg
= reason
;
2087 radiussend(r
, RADIUSSTOP
);
2091 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2093 // Save counters to dump to accounting file
2094 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2095 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2098 if (!session
[s
].die
)
2099 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2102 { // IP allocated, clear and unroute
2105 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2107 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2108 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2111 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2112 session
[s
].route
[r
].ip
= 0;
2115 if (session
[s
].ip_pool_index
== -1) // static ip
2117 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2123 // unroute IPv6, if setup
2124 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
2125 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2129 // This session was part of a bundle
2130 bundle
[b
].num_of_links
--;
2131 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2132 if(bundle
[b
].num_of_links
== 0)
2135 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2139 // Adjust the members array to accomodate the new change
2140 uint8_t mem_num
= 0;
2141 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2142 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2145 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2146 if(bundle
[b
].members
[ml
] == s
)
2151 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2152 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2154 // If the killed session is the first of the bundle,
2155 // the new first session must be stored in the cache_ipmap
2156 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2159 sessionidt new_s
= bundle
[b
].members
[0];
2162 // Add the route for this session.
2163 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2168 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2169 ip
= session
[new_s
].route
[r
].ip
;
2171 if (!prefixlen
) prefixlen
= 32;
2172 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2174 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2175 cache_ipmap(i
, new_s
);
2177 cache_ipmap(session
[new_s
].ip
, new_s
);
2180 if (session
[new_s
].ipv6prefixlen
)
2181 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2186 cluster_send_bundle(b
);
2190 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2191 throttle_session(s
, 0, 0);
2195 if (session
[s
].tunnel
== TUNNEL_ID_PPPOE
)
2197 pppoe_shutdown_session(s
);
2202 controlt
*c
= controlnew(14); // sending CDN
2206 buf
[0] = htons(cdn_result
);
2207 buf
[1] = htons(cdn_error
);
2208 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2211 control16(c
, 1, cdn_result
, 1);
2213 control16(c
, 14, s
, 1); // assigned session (our end)
2214 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2218 // update filter refcounts
2219 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2220 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2223 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2224 sess_local
[s
].lcp
.restart
= 0;
2225 sess_local
[s
].ipcp
.restart
= 0;
2226 sess_local
[s
].ipv6cp
.restart
= 0;
2227 sess_local
[s
].ccp
.restart
= 0;
2229 cluster_send_session(s
);
2232 void sendipcp(sessionidt s
, tunnelidt t
)
2234 uint8_t buf
[MAXETHER
];
2238 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2240 if (!session
[s
].unique_id
)
2242 if (!++last_id
) ++last_id
; // skip zero
2243 session
[s
].unique_id
= last_id
;
2246 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2250 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2251 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2252 q
[4] = 3; // ip address option
2253 q
[5] = 6; // option length
2254 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2255 config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] :
2256 my_address
; // send my IP
2258 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2259 restart_timer(s
, ipcp
);
2262 void sendipv6cp(sessionidt s
, tunnelidt t
)
2264 uint8_t buf
[MAXETHER
];
2268 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2270 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2274 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2275 // only send one type
2277 *(uint16_t *) (q
+ 2) = htons(14);
2278 q
[4] = 1; // interface identifier option
2279 q
[5] = 10; // option length
2280 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2281 *(uint32_t *) (q
+ 10) = 0;
2284 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2285 restart_timer(s
, ipv6cp
);
2288 static void sessionclear(sessionidt s
)
2290 memset(&session
[s
], 0, sizeof(session
[s
]));
2291 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2292 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2294 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2295 session
[s
].next
= sessionfree
;
2299 // kill a session now
2300 void sessionkill(sessionidt s
, char *reason
)
2306 if (!session
[s
].opened
) // not alive
2309 if (session
[s
].next
)
2311 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2315 if (!session
[s
].die
)
2316 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2318 if (sess_local
[s
].radius
)
2319 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2321 if (session
[s
].forwardtosession
)
2323 sessionidt sess
= session
[s
].forwardtosession
;
2324 if (session
[sess
].forwardtosession
== s
)
2326 // Shutdown the linked session also.
2327 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2331 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2333 if ((g
= grp_groupbysession(s
)))
2335 grp_removesession(g
, s
);
2339 cluster_send_session(s
);
2342 static void tunnelclear(tunnelidt t
)
2345 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2346 tunnel
[t
].state
= TUNNELFREE
;
2349 static void bundleclear(bundleidt b
)
2352 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2353 bundle
[b
].state
= BUNDLEFREE
;
2356 // kill a tunnel now
2357 static void tunnelkill(tunnelidt t
, char *reason
)
2364 tunnel
[t
].state
= TUNNELDIE
;
2366 // free control messages
2367 while ((c
= tunnel
[t
].controls
))
2369 controlt
* n
= c
->next
;
2370 tunnel
[t
].controls
= n
;
2371 tunnel
[t
].controlc
--;
2372 c
->next
= controlfree
;
2376 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2377 if (session
[s
].tunnel
== t
)
2378 sessionkill(s
, reason
);
2382 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2383 cli_tunnel_actions
[t
].action
= 0;
2384 cluster_send_tunnel(t
);
2387 // shut down a tunnel cleanly
2388 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2392 CSTAT(tunnelshutdown
);
2394 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2396 // never set up, can immediately kill
2397 tunnelkill(t
, reason
);
2400 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2403 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2404 if (session
[s
].tunnel
== t
)
2405 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2407 tunnel
[t
].state
= TUNNELDIE
;
2408 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2409 cluster_send_tunnel(t
);
2410 // TBA - should we wait for sessions to stop?
2413 controlt
*c
= controlnew(4); // sending StopCCN
2418 buf
[0] = htons(result
);
2419 buf
[1] = htons(error
);
2422 int m
= strlen(msg
);
2423 if (m
+ 4 > sizeof(buf
))
2424 m
= sizeof(buf
) - 4;
2426 memcpy(buf
+2, msg
, m
);
2430 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2433 control16(c
, 1, result
, 1);
2435 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2436 controladd(c
, 0, t
); // send the message
2440 // read and process packet on tunnel (UDP)
2441 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, uint16_t indexudpfd
)
2443 uint8_t *chapresponse
= NULL
;
2444 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2445 uint8_t *p
= buf
+ 2;
2452 LOG_HEX(5, "UDP Data", buf
, len
);
2453 STAT(tunnel_rx_packets
);
2454 INC_STAT(tunnel_rx_bytes
, len
);
2457 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2458 STAT(tunnel_rx_errors
);
2461 if ((buf
[1] & 0x0F) != 2)
2463 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2464 STAT(tunnel_rx_errors
);
2469 l
= ntohs(*(uint16_t *) p
);
2472 t
= ntohs(*(uint16_t *) p
);
2474 s
= ntohs(*(uint16_t *) p
);
2476 if (s
>= MAXSESSION
)
2478 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2479 STAT(tunnel_rx_errors
);
2484 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2485 STAT(tunnel_rx_errors
);
2488 if (t
== TUNNEL_ID_PPPOE
)
2490 LOG(1, s
, t
, "Received UDP packet with tunnel ID reserved for pppoe\n");
2491 STAT(tunnel_rx_errors
);
2496 ns
= ntohs(*(uint16_t *) p
);
2498 nr
= ntohs(*(uint16_t *) p
);
2503 uint16_t o
= ntohs(*(uint16_t *) p
);
2508 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2509 STAT(tunnel_rx_errors
);
2514 // used to time out old tunnels
2515 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2516 tunnel
[t
].lastrec
= time_now
;
2520 uint16_t message
= 0xFFFF; // message type
2522 uint8_t mandatory
= 0;
2523 uint16_t asession
= 0; // assigned session
2524 uint32_t amagic
= 0; // magic number
2525 uint8_t aflags
= 0; // flags from last LCF
2526 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2527 char called
[MAXTEL
] = ""; // called number
2528 char calling
[MAXTEL
] = ""; // calling number
2530 if (!config
->cluster_iam_master
)
2532 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
2536 // control messages must have bits 0x80|0x40|0x08
2537 // (type, length and sequence) set, and bits 0x02|0x01
2538 // (offset and priority) clear
2539 if ((*buf
& 0xCB) != 0xC8)
2541 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2542 STAT(tunnel_rx_errors
);
2546 // check for duplicate tunnel open message
2552 // Is this a duplicate of the first packet? (SCCRQ)
2554 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2556 if (tunnel
[i
].state
!= TUNNELOPENING
||
2557 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2558 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2561 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2566 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2567 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2569 // if no tunnel specified, assign one
2572 if (!(t
= new_tunnel()))
2574 LOG(1, 0, 0, "No more tunnels\n");
2575 STAT(tunnel_overflow
);
2579 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2580 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2581 tunnel
[t
].window
= 4; // default window
2582 tunnel
[t
].indexudp
= indexudpfd
;
2583 STAT(tunnel_created
);
2584 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2585 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2588 // If the 'ns' just received is not the 'nr' we're
2589 // expecting, just send an ack and drop it.
2591 // if 'ns' is less, then we got a retransmitted packet.
2592 // if 'ns' is greater than missed a packet. Either way
2593 // we should ignore it.
2594 if (ns
!= tunnel
[t
].nr
)
2596 // is this the sequence we were expecting?
2597 STAT(tunnel_rx_errors
);
2598 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2599 t
, ns
, tunnel
[t
].nr
);
2601 if (l
) // Is this not a ZLB?
2606 // check sequence of this message
2608 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2609 // some to clear maybe?
2610 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2612 controlt
*c
= tunnel
[t
].controls
;
2613 tunnel
[t
].controls
= c
->next
;
2614 tunnel
[t
].controlc
--;
2615 c
->next
= controlfree
;
2618 tunnel
[t
].try = 0; // we have progress
2621 // receiver advance (do here so quoted correctly in any sends below)
2622 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2623 if (skip
< 0) skip
= 0;
2624 if (skip
< tunnel
[t
].controlc
)
2626 // some control packets can now be sent that were previous stuck out of window
2627 int tosend
= tunnel
[t
].window
- skip
;
2628 controlt
*c
= tunnel
[t
].controls
;
2636 tunnel
[t
].try = 0; // first send
2637 tunnelsend(c
->buf
, c
->length
, t
);
2642 if (!tunnel
[t
].controlc
)
2643 tunnel
[t
].retry
= 0; // caught up
2646 { // if not a null message
2651 // Default disconnect cause/message on receipt of CDN. Set to
2652 // more specific value from attribute 1 (result code) or 46
2653 // (disconnect cause) if present below.
2654 int disc_cause_set
= 0;
2655 int disc_cause
= TERM_NAS_REQUEST
;
2656 char const *disc_reason
= "Closed (Received CDN).";
2659 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2661 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2668 LOG(1, s
, t
, "Invalid length in AVP\n");
2669 STAT(tunnel_rx_errors
);
2674 if (flags
& 0x3C) // reserved bits, should be clear
2676 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2678 result
= 2; // general error
2679 error
= 3; // reserved field non-zero
2684 if (*(uint16_t *) (b
))
2686 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2688 result
= 2; // general error
2689 error
= 6; // generic vendor-specific error
2690 msg
= "unsupported vendor-specific";
2694 mtype
= ntohs(*(uint16_t *) (b
));
2702 // handle hidden AVPs
2703 if (!*config
->l2tp_secret
)
2705 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2707 result
= 2; // general error
2708 error
= 6; // generic vendor-specific error
2709 msg
= "secret not specified";
2712 if (!session
[s
].random_vector_length
)
2714 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2716 result
= 2; // general error
2717 error
= 6; // generic
2718 msg
= "no random vector";
2723 LOG(2, s
, t
, "Short hidden AVP.\n");
2725 result
= 2; // general error
2726 error
= 2; // length is wrong
2732 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2734 orig_len
= ntohs(*(uint16_t *) b
);
2735 if (orig_len
> n
+ 2)
2737 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2741 result
= 2; // general error
2742 error
= 2; // length is wrong
2751 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2752 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2756 case 0: // message type
2757 message
= ntohs(*(uint16_t *) b
);
2758 mandatory
= flags
& 0x80;
2759 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2761 case 1: // result code
2763 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2764 char const *resdesc
= "(unknown)";
2765 char const *errdesc
= NULL
;
2770 resdesc
= l2tp_stopccn_result_code(rescode
);
2771 cause
= TERM_LOST_SERVICE
;
2773 else if (message
== 14)
2775 resdesc
= l2tp_cdn_result_code(rescode
);
2777 cause
= TERM_LOST_CARRIER
;
2779 cause
= TERM_ADMIN_RESET
;
2782 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2785 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2786 errdesc
= l2tp_error_code(errcode
);
2787 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2790 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2792 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2794 disc_cause_set
= mtype
;
2795 disc_reason
= errdesc
? errdesc
: resdesc
;
2802 case 2: // protocol version
2804 version
= ntohs(*(uint16_t *) (b
));
2805 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2806 if (version
&& version
!= 0x0100)
2807 { // allow 0.0 and 1.0
2808 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2810 result
= 5; // unspported protocol version
2811 error
= 0x0100; // supported version
2817 case 3: // framing capabilities
2819 case 4: // bearer capabilities
2821 case 5: // tie breaker
2822 // We never open tunnels, so we don't care about tie breakers
2824 case 6: // firmware revision
2826 case 7: // host name
2827 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2828 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2829 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2830 // TBA - to send to RADIUS
2832 case 8: // vendor name
2833 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2834 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2835 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2837 case 9: // assigned tunnel
2838 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2839 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2841 case 10: // rx window
2842 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2843 if (!tunnel
[t
].window
)
2844 tunnel
[t
].window
= 1; // window of 0 is silly
2845 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2847 case 11: // Challenge
2849 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2850 build_chap_response(b
, 2, n
, &chapresponse
);
2853 case 13: // Response
2854 if (tunnel
[t
].isremotelns
)
2856 chapresponse
= calloc(17, 1);
2857 memcpy(chapresponse
, b
, (n
< 17) ? n
: 16);
2858 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2861 // Why did they send a response? We never challenge.
2862 LOG(2, s
, t
, " received unexpected challenge response\n");
2865 case 14: // assigned session
2866 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2867 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2869 case 15: // call serial number
2870 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2872 case 18: // bearer type
2873 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2876 case 19: // framing type
2877 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2880 case 21: // called number
2881 memset(called
, 0, sizeof(called
));
2882 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2883 LOG(4, s
, t
, " Called <%s>\n", called
);
2885 case 22: // calling number
2886 memset(calling
, 0, sizeof(calling
));
2887 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2888 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2892 case 24: // tx connect speed
2895 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2899 // AS5300s send connect speed as a string
2901 memset(tmp
, 0, sizeof(tmp
));
2902 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2903 session
[s
].tx_connect_speed
= atol(tmp
);
2905 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2907 case 38: // rx connect speed
2910 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2914 // AS5300s send connect speed as a string
2916 memset(tmp
, 0, sizeof(tmp
));
2917 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2918 session
[s
].rx_connect_speed
= atol(tmp
);
2920 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2922 case 25: // Physical Channel ID
2924 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2925 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2928 case 29: // Proxy Authentication Type
2930 uint16_t atype
= ntohs(*(uint16_t *)b
);
2931 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2934 case 30: // Proxy Authentication Name
2937 memset(authname
, 0, sizeof(authname
));
2938 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2939 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2943 case 31: // Proxy Authentication Challenge
2945 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2948 case 32: // Proxy Authentication ID
2950 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2951 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2954 case 33: // Proxy Authentication Response
2955 LOG(4, s
, t
, " Proxy Auth Response\n");
2957 case 27: // last sent lcp
2958 { // find magic number
2959 uint8_t *p
= b
, *e
= p
+ n
;
2960 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2962 if (*p
== 5 && p
[1] == 6) // Magic-Number
2963 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2964 else if (*p
== 7) // Protocol-Field-Compression
2965 aflags
|= SESSION_PFC
;
2966 else if (*p
== 8) // Address-and-Control-Field-Compression
2967 aflags
|= SESSION_ACFC
;
2972 case 28: // last recv lcp confreq
2974 case 26: // Initial Received LCP CONFREQ
2976 case 39: // seq required - we control it as an LNS anyway...
2978 case 36: // Random Vector
2979 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2980 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2981 if (n
> sizeof(session
[s
].random_vector
))
2982 n
= sizeof(session
[s
].random_vector
);
2983 memcpy(session
[s
].random_vector
, b
, n
);
2984 session
[s
].random_vector_length
= n
;
2986 case 46: // ppp disconnect cause
2989 uint16_t code
= ntohs(*(uint16_t *) b
);
2990 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2991 uint8_t dir
= *(b
+ 4);
2993 LOG(4, s
, t
, " PPP disconnect cause "
2994 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2995 code
, proto
, dir
, n
- 5, b
+ 5);
2997 disc_cause_set
= mtype
;
3001 case 1: // admin disconnect
3002 disc_cause
= TERM_ADMIN_RESET
;
3003 disc_reason
= "Administrative disconnect";
3005 case 3: // lcp terminate
3006 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
3007 disc_cause
= TERM_USER_REQUEST
;
3008 disc_reason
= "Normal disconnection";
3010 case 4: // compulsory encryption unavailable
3011 if (dir
!= 1) break; // 1=refused by peer, 2=local
3012 disc_cause
= TERM_USER_ERROR
;
3013 disc_reason
= "Compulsory encryption refused";
3015 case 5: // lcp: fsm timeout
3016 disc_cause
= TERM_PORT_ERROR
;
3017 disc_reason
= "LCP: FSM timeout";
3019 case 6: // lcp: no recognisable lcp packets received
3020 disc_cause
= TERM_PORT_ERROR
;
3021 disc_reason
= "LCP: no recognisable LCP packets";
3023 case 7: // lcp: magic-no error (possibly looped back)
3024 disc_cause
= TERM_PORT_ERROR
;
3025 disc_reason
= "LCP: magic-no error (possible loop)";
3027 case 8: // lcp: echo request timeout
3028 disc_cause
= TERM_PORT_ERROR
;
3029 disc_reason
= "LCP: echo request timeout";
3031 case 13: // auth: fsm timeout
3032 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3033 disc_reason
= "Authentication: FSM timeout";
3035 case 15: // auth: unacceptable auth protocol
3036 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3037 disc_reason
= "Unacceptable authentication protocol";
3039 case 16: // auth: authentication failed
3040 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3041 disc_reason
= "Authentication failed";
3043 case 17: // ncp: fsm timeout
3044 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3045 disc_reason
= "NCP: FSM timeout";
3047 case 18: // ncp: no ncps available
3048 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3049 disc_reason
= "NCP: no NCPs available";
3051 case 19: // ncp: failure to converge on acceptable address
3052 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3053 disc_reason
= (dir
== 1)
3054 ? "NCP: too many Configure-Naks received from peer"
3055 : "NCP: too many Configure-Naks sent to peer";
3057 case 20: // ncp: user not permitted to use any address
3058 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3059 disc_reason
= (dir
== 1)
3060 ? "NCP: local link address not acceptable to peer"
3061 : "NCP: remote link address not acceptable";
3068 static char e
[] = "unknown AVP 0xXXXX";
3069 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
3071 result
= 2; // general error
3072 error
= 8; // unknown mandatory AVP
3073 sprintf((msg
= e
) + 14, "%04x", mtype
);
3080 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3084 case 1: // SCCRQ - Start Control Connection Request
3085 tunnel
[t
].state
= TUNNELOPENING
;
3086 LOG(3, s
, t
, "Received SCCRQ\n");
3087 if (main_quit
!= QUIT_SHUTDOWN
)
3089 LOG(3, s
, t
, "sending SCCRP\n");
3090 controlt
*c
= controlnew(2); // sending SCCRP
3091 control16(c
, 2, version
, 1); // protocol version
3092 control32(c
, 3, 3, 1); // framing
3093 controls(c
, 7, hostname
, 1); // host name
3094 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
3095 control16(c
, 9, t
, 1); // assigned tunnel
3096 controladd(c
, 0, t
); // send the resply
3100 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3104 tunnel
[t
].state
= TUNNELOPEN
;
3105 tunnel
[t
].lastrec
= time_now
;
3106 LOG(3, s
, t
, "Received SCCRP\n");
3107 if (main_quit
!= QUIT_SHUTDOWN
)
3109 if (tunnel
[t
].isremotelns
&& chapresponse
)
3113 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3114 // check authenticator
3115 if (memcmp(hash
, chapresponse
, 16) == 0)
3117 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3118 controlt
*c
= controlnew(3); // sending SCCCN
3119 controls(c
, 7, hostname
, 1); // host name
3120 controls(c
, 8, Vendor_name
, 1); // Vendor name
3121 control16(c
, 2, version
, 1); // protocol version
3122 control32(c
, 3, 3, 1); // framing Capabilities
3123 control16(c
, 9, t
, 1); // assigned tunnel
3124 controladd(c
, 0, t
); // send
3128 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3134 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3138 LOG(3, s
, t
, "Received SCCN\n");
3139 tunnel
[t
].state
= TUNNELOPEN
;
3140 tunnel
[t
].lastrec
= time_now
;
3141 controlnull(t
); // ack
3144 LOG(3, s
, t
, "Received StopCCN\n");
3145 controlnull(t
); // ack
3146 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3149 LOG(3, s
, t
, "Received HELLO\n");
3150 controlnull(t
); // simply ACK
3154 LOG(3, s
, t
, "Received OCRQ\n");
3158 LOG(3, s
, t
, "Received OCRO\n");
3162 LOG(3, s
, t
, "Received OCCN\n");
3165 LOG(3, s
, t
, "Received ICRQ\n");
3166 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3168 controlt
*c
= controlnew(11); // ICRP
3170 LOG(3, s
, t
, "Sending ICRP\n");
3173 sessionfree
= session
[s
].next
;
3174 memset(&session
[s
], 0, sizeof(session
[s
]));
3176 if (s
> config
->cluster_highest_sessionid
)
3177 config
->cluster_highest_sessionid
= s
;
3179 session
[s
].opened
= time_now
;
3180 session
[s
].tunnel
= t
;
3181 session
[s
].far
= asession
;
3182 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3183 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3184 control16(c
, 14, s
, 1); // assigned session
3185 controladd(c
, asession
, t
); // send the reply
3187 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3188 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3190 session
[s
].ppp
.phase
= Establish
;
3191 session
[s
].ppp
.lcp
= Starting
;
3193 STAT(session_created
);
3198 controlt
*c
= controlnew(14); // CDN
3199 LOG(3, s
, t
, "Sending CDN\n");
3202 STAT(session_overflow
);
3203 LOG(1, 0, t
, "No free sessions\n");
3204 control16(c
, 1, 4, 0); // temporary lack of resources
3207 control16(c
, 1, 2, 7); // shutting down, try another
3209 controladd(c
, asession
, t
); // send the message
3213 LOG(3, s
, t
, "Received ICRP\n");
3214 if (session
[s
].forwardtosession
)
3216 controlt
*c
= controlnew(12); // ICCN
3218 session
[s
].opened
= time_now
;
3219 session
[s
].tunnel
= t
;
3220 session
[s
].far
= asession
;
3221 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3223 control32(c
, 19, 1, 1); // Framing Type
3224 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3225 controladd(c
, asession
, t
); // send the message
3226 LOG(3, s
, t
, "Sending ICCN\n");
3230 LOG(3, s
, t
, "Received ICCN\n");
3231 if (amagic
== 0) amagic
= time_now
;
3232 session
[s
].magic
= amagic
; // set magic number
3233 session
[s
].flags
= aflags
; // set flags received
3234 session
[s
].mru
= PPPoE_MRU
; // default
3235 controlnull(t
); // ack
3238 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3239 sess_local
[s
].ppp_mru
= MRU
;
3241 // Set multilink options before sending initial LCP packet
3242 sess_local
[s
].mp_mrru
= 1614;
3243 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] : my_address
);
3246 change_state(s
, lcp
, RequestSent
);
3250 LOG(3, s
, t
, "Received CDN\n");
3251 controlnull(t
); // ack
3252 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3255 LOG(1, s
, t
, "Missing message type\n");
3258 STAT(tunnel_rx_errors
);
3260 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3262 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3265 if (chapresponse
) free(chapresponse
);
3266 cluster_send_tunnel(t
);
3270 LOG(4, s
, t
, " Got a ZLB ack\n");
3277 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3278 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3279 { // HDLC address header, discard
3285 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3286 STAT(tunnel_rx_errors
);
3296 proto
= ntohs(*(uint16_t *) p
);
3301 if (session
[s
].forwardtosession
)
3303 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3304 // Forward to LAC/BAS or Remote LNS session
3305 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3308 else if (config
->auth_tunnel_change_addr_src
)
3310 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3311 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3313 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3314 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3315 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3317 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3321 if (s
&& !session
[s
].opened
) // Is something wrong??
3323 if (!config
->cluster_iam_master
)
3325 // Pass it off to the master to deal with..
3326 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3330 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3331 STAT(tunnel_rx_errors
);
3335 if (proto
== PPPPAP
)
3337 session
[s
].last_packet
= time_now
;
3338 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3339 processpap(s
, t
, p
, l
);
3341 else if (proto
== PPPCHAP
)
3343 session
[s
].last_packet
= time_now
;
3344 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3345 processchap(s
, t
, p
, l
);
3347 else if (proto
== PPPLCP
)
3349 session
[s
].last_packet
= time_now
;
3350 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3351 processlcp(s
, t
, p
, l
);
3353 else if (proto
== PPPIPCP
)
3355 session
[s
].last_packet
= time_now
;
3356 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3357 processipcp(s
, t
, p
, l
);
3359 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3361 session
[s
].last_packet
= time_now
;
3362 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3363 processipv6cp(s
, t
, p
, l
);
3365 else if (proto
== PPPCCP
)
3367 session
[s
].last_packet
= time_now
;
3368 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3369 processccp(s
, t
, p
, l
);
3371 else if (proto
== PPPIP
)
3375 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3376 return; // closing session, PPP not processed
3379 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3380 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3382 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3386 processipin(s
, t
, p
, l
);
3388 else if (proto
== PPPMP
)
3392 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3393 return; // closing session, PPP not processed
3396 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3397 if (!config
->cluster_iam_master
)
3399 // The fragments reconstruction is managed by the Master.
3400 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3404 processmpin(s
, t
, p
, l
);
3406 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3410 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3411 return; // closing session, PPP not processed
3414 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3415 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3417 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3421 processipv6in(s
, t
, p
, l
);
3423 else if (session
[s
].ppp
.lcp
== Opened
)
3425 session
[s
].last_packet
= time_now
;
3426 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3427 protoreject(s
, t
, p
, l
, proto
);
3431 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3432 proto
, ppp_state(session
[s
].ppp
.lcp
));
3437 // read and process packet on tun
3438 // (i.e. this routine writes to buf[-8]).
3439 static void processtun(uint8_t * buf
, int len
)
3441 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3442 STAT(tun_rx_packets
);
3443 INC_STAT(tun_rx_bytes
, len
);
3451 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3452 STAT(tun_rx_errors
);
3456 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3457 processipout(buf
, len
);
3458 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3459 && config
->ipv6_prefix
.s6_addr
[0])
3460 processipv6out(buf
, len
);
3465 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3466 // that we look at the whole of the tunnel, radius and session tables
3468 static void regular_cleanups(double period
)
3470 // Next tunnel, radius and session to check for actions on.
3471 static tunnelidt t
= 0;
3473 static sessionidt s
= 0;
3486 // divide up tables into slices based on the last run
3487 t_slice
= config
->cluster_highest_tunnelid
* period
;
3488 r_slice
= (MAXRADIUS
- 1) * period
;
3489 s_slice
= config
->cluster_highest_sessionid
* period
;
3493 else if (t_slice
> config
->cluster_highest_tunnelid
)
3494 t_slice
= config
->cluster_highest_tunnelid
;
3498 else if (r_slice
> (MAXRADIUS
- 1))
3499 r_slice
= MAXRADIUS
- 1;
3503 else if (s_slice
> config
->cluster_highest_sessionid
)
3504 s_slice
= config
->cluster_highest_sessionid
;
3506 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3508 for (i
= 0; i
< t_slice
; i
++)
3511 if (t
> config
->cluster_highest_tunnelid
)
3514 if (t
== TUNNEL_ID_PPPOE
)
3517 // check for expired tunnels
3518 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3520 STAT(tunnel_timeout
);
3521 tunnelkill(t
, "Expired");
3525 // check for message resend
3526 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3528 // resend pending messages as timeout on reply
3529 if (tunnel
[t
].retry
<= TIME
)
3531 controlt
*c
= tunnel
[t
].controls
;
3532 uint16_t w
= tunnel
[t
].window
;
3533 tunnel
[t
].try++; // another try
3534 if (tunnel
[t
].try > 5)
3535 tunnelkill(t
, "Timeout on control message"); // game over
3539 tunnelsend(c
->buf
, c
->length
, t
);
3547 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3549 if (!config
->disable_sending_hello
)
3551 controlt
*c
= controlnew(6); // sending HELLO
3552 controladd(c
, 0, t
); // send the message
3553 LOG(3, 0, t
, "Sending HELLO message\n");
3558 // Check for tunnel changes requested from the CLI
3559 if ((a
= cli_tunnel_actions
[t
].action
))
3561 cli_tunnel_actions
[t
].action
= 0;
3562 if (a
& CLI_TUN_KILL
)
3564 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3565 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3571 for (i
= 0; i
< r_slice
; i
++)
3577 if (!radius
[r
].state
)
3580 if (radius
[r
].retry
<= TIME
)
3587 for (i
= 0; i
< s_slice
; i
++)
3590 if (s
> config
->cluster_highest_sessionid
)
3593 if (!session
[s
].opened
) // Session isn't in use
3596 // check for expired sessions
3599 if (session
[s
].die
<= TIME
)
3601 sessionkill(s
, "Expired");
3608 if (sess_local
[s
].lcp
.restart
<= time_now
)
3610 int next_state
= session
[s
].ppp
.lcp
;
3611 switch (session
[s
].ppp
.lcp
)
3615 next_state
= RequestSent
;
3618 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3620 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3621 sendlcp(s
, session
[s
].tunnel
);
3622 change_state(s
, lcp
, next_state
);
3626 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3627 STAT(session_timeout
);
3637 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3639 int next_state
= session
[s
].ppp
.ipcp
;
3640 switch (session
[s
].ppp
.ipcp
)
3644 next_state
= RequestSent
;
3647 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3649 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3650 sendipcp(s
, session
[s
].tunnel
);
3651 change_state(s
, ipcp
, next_state
);
3655 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3656 STAT(session_timeout
);
3666 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3668 int next_state
= session
[s
].ppp
.ipv6cp
;
3669 switch (session
[s
].ppp
.ipv6cp
)
3673 next_state
= RequestSent
;
3676 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3678 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3679 sendipv6cp(s
, session
[s
].tunnel
);
3680 change_state(s
, ipv6cp
, next_state
);
3684 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3685 change_state(s
, ipv6cp
, Stopped
);
3692 if (sess_local
[s
].ccp
.restart
<= time_now
)
3694 int next_state
= session
[s
].ppp
.ccp
;
3695 switch (session
[s
].ppp
.ccp
)
3699 next_state
= RequestSent
;
3702 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3704 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3705 sendccp(s
, session
[s
].tunnel
);
3706 change_state(s
, ccp
, next_state
);
3710 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3711 change_state(s
, ccp
, Stopped
);
3718 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3719 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3721 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3722 STAT(session_timeout
);
3727 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3728 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= config
->echo_timeout
) &&
3729 (time_now
- sess_local
[s
].last_echo
>= config
->echo_timeout
))
3731 uint8_t b
[MAXETHER
];
3733 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3737 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3738 *(uint16_t *)(q
+ 2) = htons(8); // Length
3739 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3741 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3742 (int)(time_now
- session
[s
].last_packet
));
3744 tunnelsend(b
, (q
- b
) + 8, session
[s
].tunnel
); // send it
3745 sess_local
[s
].last_echo
= time_now
;
3749 // Drop sessions who have reached session_timeout seconds
3750 if (session
[s
].session_timeout
)
3752 bundleidt bid
= session
[s
].bundle
;
3755 if (time_now
- bundle
[bid
].last_check
>= 1)
3757 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3758 bundle
[bid
].last_check
= time_now
;
3759 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3762 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3764 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3771 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3773 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3779 // Drop sessions who have reached idle_timeout seconds
3780 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3782 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3783 STAT(session_timeout
);
3788 // Check for actions requested from the CLI
3789 if ((a
= cli_session_actions
[s
].action
))
3793 cli_session_actions
[s
].action
= 0;
3794 if (a
& CLI_SESS_KILL
)
3796 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3797 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3798 a
= 0; // dead, no need to check for other actions
3802 if (a
& CLI_SESS_NOSNOOP
)
3804 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3805 session
[s
].snoop_ip
= 0;
3806 session
[s
].snoop_port
= 0;
3810 else if (a
& CLI_SESS_SNOOP
)
3812 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3813 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3814 cli_session_actions
[s
].snoop_port
);
3816 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3817 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3822 if (a
& CLI_SESS_NOTHROTTLE
)
3824 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3825 throttle_session(s
, 0, 0);
3829 else if (a
& CLI_SESS_THROTTLE
)
3831 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3832 cli_session_actions
[s
].throttle_in
,
3833 cli_session_actions
[s
].throttle_out
);
3835 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3840 if (a
& CLI_SESS_NOFILTER
)
3842 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3843 filter_session(s
, 0, 0);
3847 else if (a
& CLI_SESS_FILTER
)
3849 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3850 cli_session_actions
[s
].filter_in
,
3851 cli_session_actions
[s
].filter_out
);
3853 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3859 cluster_send_session(s
);
3862 // RADIUS interim accounting
3863 if (config
->radius_accounting
&& config
->radius_interim
> 0
3864 && session
[s
].ip
&& !session
[s
].walled_garden
3865 && !sess_local
[s
].radius
// RADIUS already in progress
3866 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3867 && session
[s
].flags
& SESSION_STARTED
)
3869 int rad
= radiusnew(s
);
3872 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3873 STAT(radius_overflow
);
3877 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3878 session
[s
].user
, session
[s
].unique_id
);
3880 radiussend(rad
, RADIUSINTERIM
);
3881 sess_local
[s
].last_interim
= time_now
;
3886 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3887 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3891 // Are we in the middle of a tunnel update, or radius
3894 static int still_busy(void)
3897 static clockt last_talked
= 0;
3898 static clockt start_busy_wait
= 0;
3901 static time_t stopped_bgp
= 0;
3906 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3908 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3909 if (bgp_peers
[i
].state
== Established
)
3910 bgp_stop(&bgp_peers
[i
]);
3912 stopped_bgp
= time_now
;
3914 if (!config
->cluster_iam_master
)
3916 // we don't want to become master
3917 cluster_send_ping(0);
3923 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3928 if (!config
->cluster_iam_master
)
3931 if (main_quit
== QUIT_SHUTDOWN
)
3933 static int dropped
= 0;
3938 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3939 for (i
= 1; i
< MAXTUNNEL
; i
++)
3940 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3941 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3947 if (start_busy_wait
== 0)
3948 start_busy_wait
= TIME
;
3950 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3952 if (!tunnel
[i
].controlc
)
3955 if (last_talked
!= TIME
)
3957 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3963 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3964 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3966 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3970 for (i
= 1; i
< MAXRADIUS
; i
++)
3972 if (radius
[i
].state
== RADIUSNULL
)
3974 if (radius
[i
].state
== RADIUSWAIT
)
3977 if (last_talked
!= TIME
)
3979 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3989 # include <sys/epoll.h>
3991 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3992 # include "fake_epoll.h"
3995 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
3996 #define BASE_FDS (9 + MAX_UDPFD)
3998 // additional polled fds
4000 # define EXTRA_FDS BGP_NUM_PEERS
4002 # define EXTRA_FDS 0
4005 // main loop - gets packets on tun or udp and processes them
4006 static void mainloop(void)
4010 uint8_t *p
= buf
+ 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4011 // and the forwarded pppoe session
4012 int size_bufp
= sizeof(buf
) - 32;
4013 clockt next_cluster_ping
= 0; // send initial ping immediately
4014 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
4015 int maxevent
= sizeof(events
)/sizeof(*events
);
4017 if ((epollfd
= epoll_create(maxevent
)) < 0)
4019 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
4023 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d , udplacfd=%d, pppoefd=%d, pppoesessfd=%d\n",
4024 clifd
, cluster_sockfd
, tunfd
, udpfd
[0], controlfd
, daefd
, nlfd
, udplacfd
, pppoediscfd
, pppoesessfd
);
4026 /* setup our fds to poll for input */
4028 static struct event_data d
[BASE_FDS
];
4029 struct epoll_event e
;
4036 d
[i
].type
= FD_TYPE_CLI
;
4037 e
.data
.ptr
= &d
[i
++];
4038 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
4041 d
[i
].type
= FD_TYPE_CLUSTER
;
4042 e
.data
.ptr
= &d
[i
++];
4043 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
4045 d
[i
].type
= FD_TYPE_TUN
;
4046 e
.data
.ptr
= &d
[i
++];
4047 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
4049 d
[i
].type
= FD_TYPE_CONTROL
;
4050 e
.data
.ptr
= &d
[i
++];
4051 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
4053 d
[i
].type
= FD_TYPE_DAE
;
4054 e
.data
.ptr
= &d
[i
++];
4055 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
4057 d
[i
].type
= FD_TYPE_NETLINK
;
4058 e
.data
.ptr
= &d
[i
++];
4059 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
4061 d
[i
].type
= FD_TYPE_PPPOEDISC
;
4062 e
.data
.ptr
= &d
[i
++];
4063 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoediscfd
, &e
);
4065 d
[i
].type
= FD_TYPE_PPPOESESS
;
4066 e
.data
.ptr
= &d
[i
++];
4067 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoesessfd
, &e
);
4069 for (j
= 0; j
< config
->nbudpfd
; j
++)
4071 d
[i
].type
= FD_TYPE_UDP
;
4073 e
.data
.ptr
= &d
[i
++];
4074 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
[j
], &e
);
4079 signal(SIGPIPE
, SIG_IGN
);
4080 bgp_setup(config
->as_number
);
4081 if (config
->bind_address
)
4082 bgp_add_route(config
->bind_address
, 0xffffffff);
4084 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4086 if (config
->neighbour
[i
].name
[0])
4087 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4088 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4089 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4090 0); /* 0 = routing disabled */
4094 while (!main_quit
|| still_busy())
4104 config
->reload_config
++;
4107 if (config
->reload_config
)
4109 config
->reload_config
= 0;
4117 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4118 STAT(select_called
);
4123 if (errno
== EINTR
||
4124 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4127 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4133 struct sockaddr_in addr
;
4134 struct in_addr local
;
4137 int udp_ready
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4138 int pppoesess_ready
= 0;
4139 int pppoesess_pkts
= 0;
4141 int cluster_ready
= 0;
4142 int udp_pkts
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4144 int cluster_pkts
= 0;
4146 uint32_t bgp_events
[BGP_NUM_PEERS
];
4147 memset(bgp_events
, 0, sizeof(bgp_events
));
4150 for (c
= n
, i
= 0; i
< c
; i
++)
4152 struct event_data
*d
= events
[i
].data
.ptr
;
4156 case FD_TYPE_CLI
: // CLI connections
4160 alen
= sizeof(addr
);
4161 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4167 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4173 // these are handled below, with multiple interleaved reads
4174 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4175 case FD_TYPE_TUN
: tun_ready
++; break;
4176 case FD_TYPE_UDP
: udp_ready
[d
->index
]++; break;
4177 case FD_TYPE_PPPOESESS
: pppoesess_ready
++; break;
4179 case FD_TYPE_PPPOEDISC
: // pppoe discovery
4180 s
= read(pppoediscfd
, p
, size_bufp
);
4181 if (s
> 0) process_pppoe_disc(p
, s
);
4185 case FD_TYPE_CONTROL
: // nsctl commands
4186 alen
= sizeof(addr
);
4187 s
= recvfromto(controlfd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4188 if (s
> 0) processcontrol(p
, s
, &addr
, alen
, &local
);
4192 case FD_TYPE_DAE
: // DAE requests
4193 alen
= sizeof(addr
);
4194 s
= recvfromto(daefd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4195 if (s
> 0) processdae(p
, s
, &addr
, alen
, &local
);
4199 case FD_TYPE_RADIUS
: // RADIUS response
4200 alen
= sizeof(addr
);
4201 s
= recvfrom(radfds
[d
->index
], p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4202 if (s
>= 0 && config
->cluster_iam_master
)
4204 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4205 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4206 processrad(p
, s
, d
->index
);
4208 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4209 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4217 bgp_events
[d
->index
] = events
[i
].events
;
4222 case FD_TYPE_NETLINK
:
4224 struct nlmsghdr
*nh
= (struct nlmsghdr
*)p
;
4225 s
= netlink_recv(p
, size_bufp
);
4226 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4228 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4231 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4233 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4237 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4242 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
);
4248 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4253 bgp_process(bgp_events
);
4256 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4258 for (j
= 0; j
< config
->nbudpfd
; j
++)
4260 // L2TP and L2TP REMOTE LNS
4263 alen
= sizeof(addr
);
4264 if ((s
= recvfrom(udpfd
[j
], p
, size_bufp
, 0, (void *) &addr
, &alen
)) > 0)
4266 processudp(p
, s
, &addr
, j
);
4280 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4293 if (pppoesess_ready
)
4295 if ((s
= read(pppoesessfd
, p
, size_bufp
)) > 0)
4297 process_pppoe_sess(p
, s
);
4302 pppoesess_ready
= 0;
4310 alen
= sizeof(addr
);
4311 if ((s
= recvfrom(cluster_sockfd
, p
, size_bufp
, MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4313 processcluster(p
, s
, addr
.sin_addr
.s_addr
);
4324 if (udp_pkts
[0] > 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4325 STAT(multi_read_used
);
4327 if (c
>= config
->multi_read_count
)
4329 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4330 config
->multi_read_count
, udp_pkts
[0], tun_pkts
, cluster_pkts
, pppoesess_pkts
);
4331 STAT(multi_read_exceeded
);
4337 /* no event received, but timers could still have expired */
4338 bgp_process_peers_timers();
4343 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4345 // Log current traffic stats
4346 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4347 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4348 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4349 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4350 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4352 udp_tx
= udp_rx
= 0;
4353 udp_rx_pkt
= eth_rx_pkt
= 0;
4354 eth_tx
= eth_rx
= 0;
4357 if (config
->dump_speed
)
4358 printf("%s\n", config
->bandwidth
);
4360 // Update the internal time counter
4361 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4365 struct param_timer p
= { time_now
};
4366 run_plugins(PLUGIN_TIMER
, &p
);
4370 // Runs on every machine (master and slaves).
4371 if (next_cluster_ping
<= TIME
)
4373 // Check to see which of the cluster is still alive..
4375 cluster_send_ping(basetime
); // Only does anything if we're a slave
4376 cluster_check_master(); // ditto.
4378 cluster_heartbeat(); // Only does anything if we're a master.
4379 cluster_check_slaves(); // ditto.
4381 master_update_counts(); // If we're a slave, send our byte counters to our master.
4383 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4384 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4386 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4389 if (!config
->cluster_iam_master
)
4392 // Run token bucket filtering queue..
4393 // Only run it every 1/10th of a second.
4395 static clockt last_run
= 0;
4396 if (last_run
!= TIME
)
4403 // Handle timeouts, retries etc.
4405 static double last_clean
= 0;
4409 TIME
= now(&this_clean
);
4410 diff
= this_clean
- last_clean
;
4412 // Run during idle time (after we've handled
4413 // all incoming packets) or every 1/10th sec
4414 if (!more
|| diff
> 0.1)
4416 regular_cleanups(diff
);
4417 last_clean
= this_clean
;
4421 if (*config
->accounting_dir
)
4423 static clockt next_acct
= 0;
4424 static clockt next_shut_acct
= 0;
4426 if (next_acct
<= TIME
)
4428 // Dump accounting data
4429 next_acct
= TIME
+ ACCT_TIME
;
4430 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4433 else if (next_shut_acct
<= TIME
)
4435 // Dump accounting data for shutdown sessions
4436 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4443 // Are we the master and shutting down??
4444 if (config
->cluster_iam_master
)
4445 cluster_heartbeat(); // Flush any queued changes..
4447 // Ok. Notify everyone we're shutting down. If we're
4448 // the master, this will force an election.
4449 cluster_send_ping(0);
4452 // Important!!! We MUST not process any packets past this point!
4453 LOG(1, 0, 0, "Shutdown complete\n");
4456 static void stripdomain(char *host
)
4460 if ((p
= strchr(host
, '.')))
4466 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4472 while (fgets(buf
, sizeof(buf
), resolv
))
4474 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4477 if (!isspace(buf
[6]))
4481 while (isspace(*b
)) b
++;
4486 while (*b
&& !isspace(*b
)) b
++;
4488 if (buf
[0] == 'd') // domain is canonical
4494 // first search line
4497 // hold, may be subsequent domain line
4498 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4509 int hl
= strlen(host
);
4510 int dl
= strlen(domain
);
4511 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4512 host
[hl
-dl
- 1] = 0;
4516 *p
= 0; // everything after first dot
4521 // Init data structures
4522 static void initdata(int optdebug
, char *optconfig
)
4526 if (!(config
= shared_malloc(sizeof(configt
))))
4528 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4532 memset(config
, 0, sizeof(configt
));
4533 time(&config
->start_time
);
4534 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4535 config
->debug
= optdebug
;
4536 config
->num_tbfs
= MAXTBFS
;
4537 config
->rl_rate
= 28; // 28kbps
4538 config
->cluster_mcast_ttl
= 1;
4539 config
->cluster_master_min_adv
= 1;
4540 config
->ppp_restart_time
= 3;
4541 config
->ppp_max_configure
= 10;
4542 config
->ppp_max_failure
= 5;
4543 config
->kill_timedout_sessions
= 1;
4544 strcpy(config
->random_device
, RANDOMDEVICE
);
4545 // Set default value echo_timeout and idle_echo_timeout
4546 config
->echo_timeout
= ECHO_TIMEOUT
;
4547 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4549 log_stream
= stderr
;
4552 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4554 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4557 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4560 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4562 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4565 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4567 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4570 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4572 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4575 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4577 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4580 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4582 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4586 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4588 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4592 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4594 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4598 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4600 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4604 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4606 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4609 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4611 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4613 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4616 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4618 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4620 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4623 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4625 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4626 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4627 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4628 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4629 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4631 // Put all the sessions on the free list marked as undefined.
4632 for (i
= 1; i
< MAXSESSION
; i
++)
4634 session
[i
].next
= i
+ 1;
4635 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4637 session
[MAXSESSION
- 1].next
= 0;
4640 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4641 for (i
= 1; i
< MAXTUNNEL
; i
++)
4642 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4644 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4645 bundle
[i
].state
= BUNDLEUNDEF
;
4650 // Grab my hostname unless it's been specified
4651 gethostname(hostname
, sizeof(hostname
));
4652 stripdomain(hostname
);
4655 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4658 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4660 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4665 lac_initremotelnsdata();
4670 static int assign_ip_address(sessionidt s
)
4674 time_t best_time
= time_now
;
4675 char *u
= session
[s
].user
;
4679 CSTAT(assign_ip_address
);
4681 for (i
= 1; i
< ip_pool_size
; i
++)
4683 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4686 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4693 if (ip_address_pool
[i
].last
< best_time
)
4696 if (!(best_time
= ip_address_pool
[i
].last
))
4697 break; // never used, grab this one
4703 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4707 session
[s
].ip
= ip_address_pool
[best
].address
;
4708 session
[s
].ip_pool_index
= best
;
4709 ip_address_pool
[best
].assigned
= 1;
4710 ip_address_pool
[best
].last
= time_now
;
4711 ip_address_pool
[best
].session
= s
;
4712 if (session
[s
].walled_garden
)
4713 /* Don't track addresses of users in walled garden (note: this
4714 means that their address isn't "sticky" even if they get
4716 ip_address_pool
[best
].user
[0] = 0;
4718 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4721 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4722 reuse
? "Reusing" : "Allocating", best
);
4727 static void free_ip_address(sessionidt s
)
4729 int i
= session
[s
].ip_pool_index
;
4732 CSTAT(free_ip_address
);
4735 return; // what the?
4737 if (i
< 0) // Is this actually part of the ip pool?
4741 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4743 ip_address_pool
[i
].assigned
= 0;
4744 ip_address_pool
[i
].session
= 0;
4745 ip_address_pool
[i
].last
= time_now
;
4749 // Fsck the address pool against the session table.
4750 // Normally only called when we become a master.
4752 // This isn't perfect: We aren't keep tracking of which
4753 // users used to have an IP address.
4755 void rebuild_address_pool(void)
4760 // Zero the IP pool allocation, and build
4761 // a map from IP address to pool index.
4762 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4764 ip_address_pool
[i
].assigned
= 0;
4765 ip_address_pool
[i
].session
= 0;
4766 if (!ip_address_pool
[i
].address
)
4769 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4772 for (i
= 0; i
< MAXSESSION
; ++i
)
4775 if (!(session
[i
].opened
&& session
[i
].ip
))
4778 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4780 if (session
[i
].ip_pool_index
< 0)
4782 // Not allocated out of the pool.
4783 if (ipid
< 1) // Not found in the pool either? good.
4786 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4787 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4789 // Fall through and process it as part of the pool.
4793 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4795 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4797 session
[i
].ip_pool_index
= ipid
;
4801 ip_address_pool
[ipid
].assigned
= 1;
4802 ip_address_pool
[ipid
].session
= i
;
4803 ip_address_pool
[ipid
].last
= time_now
;
4804 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4805 session
[i
].ip_pool_index
= ipid
;
4806 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4811 // Fix the address pool to match a changed session.
4812 // (usually when the master sends us an update).
4813 static void fix_address_pool(int sid
)
4817 ipid
= session
[sid
].ip_pool_index
;
4819 if (ipid
> ip_pool_size
)
4820 return; // Ignore it. rebuild_address_pool will fix it up.
4822 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4823 return; // Just ignore it. rebuild_address_pool will take care of it.
4825 ip_address_pool
[ipid
].assigned
= 1;
4826 ip_address_pool
[ipid
].session
= sid
;
4827 ip_address_pool
[ipid
].last
= time_now
;
4828 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4832 // Add a block of addresses to the IP pool to hand out.
4834 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4838 prefixlen
= 32; // Host route only.
4840 addr
&= 0xffffffff << (32 - prefixlen
);
4842 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4845 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4847 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4848 continue; // Skip 0 and broadcast addresses.
4850 ip_address_pool
[ip_pool_size
].address
= i
;
4851 ip_address_pool
[ip_pool_size
].assigned
= 0;
4853 if (ip_pool_size
>= MAXIPPOOL
)
4855 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4861 // Initialize the IP address pool
4862 static void initippool()
4867 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4869 if (!(f
= fopen(IPPOOLFILE
, "r")))
4871 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4875 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4878 buf
[4095] = 0; // Force it to be zero terminated/
4880 if (*buf
== '#' || *buf
== '\n')
4881 continue; // Skip comments / blank lines
4882 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4883 if ((p
= (char *)strchr(buf
, ':')))
4887 src
= inet_addr(buf
);
4888 if (src
== INADDR_NONE
)
4890 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4893 // This entry is for a specific IP only
4894 if (src
!= config
->bind_address
)
4899 if ((p
= (char *)strchr(pool
, '/')))
4903 in_addr_t start
= 0;
4905 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4907 if (!*p
|| !(numbits
= atoi(p
)))
4909 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4912 start
= ntohl(inet_addr(pool
));
4914 // Add a static route for this pool
4915 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4916 fmtaddr(htonl(start
), 0), numbits
);
4918 routeset(0, start
, numbits
, 0, 1);
4920 add_to_ip_pool(start
, numbits
);
4924 // It's a single ip address
4925 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4929 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4932 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4934 struct sockaddr_in snoop_addr
= {0};
4935 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4938 snoop_addr
.sin_family
= AF_INET
;
4939 snoop_addr
.sin_addr
.s_addr
= destination
;
4940 snoop_addr
.sin_port
= ntohs(port
);
4942 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4943 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4944 htons(snoop_addr
.sin_port
));
4946 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4947 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4949 STAT(packets_snooped
);
4952 static int dump_session(FILE **f
, sessiont
*s
)
4954 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4959 char filename
[1024];
4961 time_t now
= time(NULL
);
4963 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4964 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4966 if (!(*f
= fopen(filename
, "w")))
4968 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4972 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4973 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4978 "# format: username ip qos uptxoctets downrxoctets\n",
4980 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
4985 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4986 fprintf(*f
, "%s %s %d %u %u\n",
4987 s
->user
, // username
4988 fmtaddr(htonl(s
->ip
), 0), // ip
4989 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4990 (uint32_t) s
->cin_delta
, // uptxoctets
4991 (uint32_t) s
->cout_delta
); // downrxoctets
4993 s
->cin_delta
= s
->cout_delta
= 0;
4998 static void dump_acct_info(int all
)
5004 CSTAT(dump_acct_info
);
5008 for (i
= 0; i
< shut_acct_n
; i
++)
5009 dump_session(&f
, &shut_acct
[i
]);
5015 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5016 dump_session(&f
, &session
[i
]);
5023 int main(int argc
, char *argv
[])
5027 char *optconfig
= CONFIGFILE
;
5029 time(&basetime
); // start clock
5032 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
5037 if (fork()) exit(0);
5039 freopen("/dev/null", "r", stdin
);
5040 freopen("/dev/null", "w", stdout
);
5041 freopen("/dev/null", "w", stderr
);
5050 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
5053 printf("Args are:\n"
5054 "\t-d\t\tDetach from terminal\n"
5055 "\t-c <file>\tConfig file\n"
5056 "\t-h <hostname>\tForce hostname\n"
5064 // Start the timer routine off
5066 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5069 initdata(optdebug
, optconfig
);
5073 /* set hostname /after/ having read the config file */
5074 if (*config
->hostname
)
5075 strcpy(hostname
, config
->hostname
);
5076 cli_init_complete(hostname
);
5078 init_tbf(config
->num_tbfs
);
5080 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5081 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5082 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5085 rlim
.rlim_cur
= RLIM_INFINITY
;
5086 rlim
.rlim_max
= RLIM_INFINITY
;
5087 // Remove the maximum core size
5088 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5089 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5091 // Make core dumps go to /tmp
5095 if (config
->scheduler_fifo
)
5098 struct sched_param params
= {0};
5099 params
.sched_priority
= 1;
5101 if (get_nprocs() < 2)
5103 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5104 config
->scheduler_fifo
= 0;
5108 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5110 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5114 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5115 config
->scheduler_fifo
= 0;
5122 /* Set up the cluster communications port. */
5123 if (cluster_init() < 0)
5127 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5129 if (*config
->pppoe_if_to_bind
)
5132 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config
->pppoe_if_to_bind
);
5135 if (!config
->nbmultiaddress
)
5137 config
->bind_n_address
[0] = config
->bind_address
;
5138 config
->nbmultiaddress
++;
5140 config
->nbudpfd
= config
->nbmultiaddress
;
5141 for (i
= 0; i
< config
->nbudpfd
; i
++)
5142 initudp(&udpfd
[i
], config
->bind_n_address
[i
]);
5144 config
->indexlacudpfd
= config
->nbudpfd
;
5145 udpfd
[config
->indexlacudpfd
] = udplacfd
;
5152 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
5159 unsigned seed
= time_now
^ getpid();
5160 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5164 signal(SIGHUP
, sighup_handler
);
5165 signal(SIGCHLD
, sigchild_handler
);
5166 signal(SIGTERM
, shutdown_handler
);
5167 signal(SIGINT
, shutdown_handler
);
5168 signal(SIGQUIT
, shutdown_handler
);
5170 // Prevent us from getting paged out
5171 if (config
->lock_pages
)
5173 if (!mlockall(MCL_CURRENT
))
5174 LOG(1, 0, 0, "Locking pages into memory\n");
5176 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5179 //LOG(3, 0, 0, "Debug sizeof struct: sessiont %lu, tunnelt %lu, bundlet %lu, groupsesst %lu\n",
5180 // sizeof(sessiont), sizeof(tunnelt), sizeof(bundlet), sizeof(groupsesst));
5184 /* remove plugins (so cleanup code gets run) */
5187 // Remove the PID file if we wrote it
5188 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5189 unlink(config
->pid_file
);
5191 /* kill CLI children */
5192 signal(SIGTERM
, SIG_IGN
);
5197 static void sighup_handler(int sig
)
5202 static void shutdown_handler(int sig
)
5204 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5207 static void sigchild_handler(int sig
)
5209 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5213 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5216 *challenge_response
= NULL
;
5218 if (!*config
->l2tp_secret
)
5220 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5224 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5226 *challenge_response
= calloc(17, 1);
5229 MD5_Update(&ctx
, &id
, 1);
5230 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5231 MD5_Update(&ctx
, challenge
, challenge_length
);
5232 MD5_Final(*challenge_response
, &ctx
);
5237 static int facility_value(char *name
)
5240 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5242 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5243 return facilitynames
[i
].c_val
;
5248 static void update_config()
5252 static int timeout
= 0;
5253 static int interval
= 0;
5260 if (log_stream
!= stderr
)
5266 if (*config
->log_filename
)
5268 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5270 char *p
= config
->log_filename
+ 7;
5273 openlog("l2tpns", LOG_PID
, facility_value(p
));
5277 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5279 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5281 fseek(log_stream
, 0, SEEK_END
);
5282 setbuf(log_stream
, NULL
);
5286 log_stream
= stderr
;
5287 setbuf(log_stream
, NULL
);
5293 log_stream
= stderr
;
5294 setbuf(log_stream
, NULL
);
5297 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5298 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5300 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5301 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5302 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5304 // reset MRU/MSS globals
5305 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5306 if (MRU
> PPPoE_MRU
)
5309 MSS
= MRU
- TCP_HDRS
;
5312 config
->numradiusservers
= 0;
5313 for (i
= 0; i
< MAXRADSERVER
; i
++)
5314 if (config
->radiusserver
[i
])
5316 config
->numradiusservers
++;
5317 // Set radius port: if not set, take the port from the
5318 // first radius server. For the first radius server,
5319 // take the #defined default value from l2tpns.h
5321 // test twice, In case someone works with
5322 // a secondary radius server without defining
5323 // a primary one, this will work even then.
5324 if (i
> 0 && !config
->radiusport
[i
])
5325 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5326 if (!config
->radiusport
[i
])
5327 config
->radiusport
[i
] = RADPORT
;
5330 if (!config
->numradiusservers
)
5331 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5333 // parse radius_authtypes_s
5334 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5335 p
= config
->radius_authtypes_s
;
5338 char *s
= strpbrk(p
, " \t,");
5344 while (*s
== ' ' || *s
== '\t')
5351 if (!strncasecmp("chap", p
, strlen(p
)))
5353 else if (!strncasecmp("pap", p
, strlen(p
)))
5356 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5358 config
->radius_authtypes
|= type
;
5359 if (!config
->radius_authprefer
)
5360 config
->radius_authprefer
= type
;
5365 if (!config
->radius_authtypes
)
5367 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5368 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5371 // normalise radius_authtypes_s
5372 if (config
->radius_authprefer
== AUTHPAP
)
5374 strcpy(config
->radius_authtypes_s
, "pap");
5375 if (config
->radius_authtypes
& AUTHCHAP
)
5376 strcat(config
->radius_authtypes_s
, ", chap");
5380 strcpy(config
->radius_authtypes_s
, "chap");
5381 if (config
->radius_authtypes
& AUTHPAP
)
5382 strcat(config
->radius_authtypes_s
, ", pap");
5385 if (!config
->radius_dae_port
)
5386 config
->radius_dae_port
= DAEPORT
;
5388 if(!config
->bind_portremotelns
)
5389 config
->bind_portremotelns
= L2TPLACPORT
;
5390 if(!config
->bind_address_remotelns
)
5391 config
->bind_address_remotelns
= INADDR_ANY
;
5393 if (*config
->bind_multi_address
)
5395 char *sip
= config
->bind_multi_address
;
5397 char *e
= config
->bind_multi_address
+ strlen(config
->bind_multi_address
);
5398 config
->nbmultiaddress
= 0;
5400 while (*sip
&& (sip
< e
))
5405 while (n
< e
&& (*n
== ',' || *n
== ' ')) n
++;
5407 while (n
< e
&& (isdigit(*n
) || *n
== '.'))
5415 u
= u
* 10 + *n
- '0';
5423 config
->bind_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5424 config
->iftun_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5425 config
->nbmultiaddress
++;
5426 LOG(1, 0, 0, "Bind address %s\n", fmtaddr(htonl(ip
), 0));
5432 if (config
->nbmultiaddress
>= 1)
5434 config
->bind_address
= config
->bind_n_address
[0];
5435 config
->iftun_address
= config
->bind_address
;
5439 if(!config
->iftun_address
)
5441 config
->iftun_address
= config
->bind_address
;
5442 config
->iftun_n_address
[0] = config
->iftun_address
;
5445 if (!*config
->pppoe_ac_name
)
5446 strncpy(config
->pppoe_ac_name
, DEFAULT_PPPOE_AC_NAME
, sizeof(config
->pppoe_ac_name
) - 1);
5448 // re-initialise the random number source
5449 initrandom(config
->random_device
);
5452 for (i
= 0; i
< MAXPLUGINS
; i
++)
5454 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5457 if (*config
->plugins
[i
])
5460 add_plugin(config
->plugins
[i
]);
5462 else if (*config
->old_plugins
[i
])
5465 remove_plugin(config
->old_plugins
[i
]);
5470 guest_accounts_num
= 0;
5471 char *p2
= config
->guest_user
;
5474 char *s
= strpbrk(p2
, " \t,");
5478 while (*s
== ' ' || *s
== '\t')
5485 strcpy(guest_users
[guest_accounts_num
], p2
);
5486 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5487 guest_accounts_num
++;
5490 // Rebuild the guest_user array
5491 strcpy(config
->guest_user
, "");
5493 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5495 strcat(config
->guest_user
, guest_users
[ui
]);
5496 if (ui
<guest_accounts_num
-1)
5498 strcat(config
->guest_user
, ",");
5503 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5504 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5505 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5506 if (!*config
->cluster_interface
)
5507 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5509 if (!config
->cluster_hb_interval
)
5510 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5512 if (!config
->cluster_hb_timeout
)
5513 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5515 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5517 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5518 // late, ensure we're sufficiently larger than that
5519 int t
= 4 * config
->cluster_hb_interval
+ 11;
5521 if (config
->cluster_hb_timeout
< t
)
5523 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5524 config
->cluster_hb_timeout
= t
;
5527 // Push timing changes to the slaves immediately if we're the master
5528 if (config
->cluster_iam_master
)
5529 cluster_heartbeat();
5531 interval
= config
->cluster_hb_interval
;
5532 timeout
= config
->cluster_hb_timeout
;
5536 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5539 if ((f
= fopen(config
->pid_file
, "w")))
5541 fprintf(f
, "%d\n", getpid());
5543 config
->wrote_pid
= 1;
5547 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5552 static void read_config_file()
5556 if (!config
->config_file
) return;
5557 if (!(f
= fopen(config
->config_file
, "r")))
5559 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5563 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5565 LOG(3, 0, 0, "Done reading config file\n");
5569 int sessionsetup(sessionidt s
, tunnelidt t
)
5571 // A session now exists, set it up
5577 CSTAT(sessionsetup
);
5579 LOG(3, s
, t
, "Doing session setup for session\n");
5581 // Join a bundle if the MRRU option is accepted
5582 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5584 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5585 if (join_bundle(s
) > 0)
5586 cluster_send_bundle(session
[s
].bundle
);
5589 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5590 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5597 assign_ip_address(s
);
5600 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5601 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5604 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5605 fmtaddr(htonl(session
[s
].ip
), 0));
5608 // Make sure this is right
5609 session
[s
].tunnel
= t
;
5611 // zap old sessions with same IP and/or username
5612 // Don't kill gardened sessions - doing so leads to a DoS
5613 // from someone who doesn't need to know the password
5616 user
= session
[s
].user
;
5617 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5619 if (i
== s
) continue;
5620 if (!session
[s
].opened
) break;
5621 // Allow duplicate sessions for multilink ones of the same bundle.
5622 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5624 if (ip
== session
[i
].ip
)
5626 sessionshutdown(i
, "Duplicate IP address", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5630 if (config
->allow_duplicate_users
) continue;
5631 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5635 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5637 if (!strcasecmp(user
, guest_users
[gu
]))
5643 if (found
) continue;
5645 // Drop the new session in case of duplicate sessionss, not the old one.
5646 if (!strcasecmp(user
, session
[i
].user
))
5647 sessionshutdown(i
, "Duplicate session for users", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5651 // no need to set a route for the same IP address of the bundle
5652 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5657 // Add the route for this session.
5658 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5660 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5661 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5664 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5667 // Static IPs need to be routed if not already
5668 // convered by a Framed-Route. Anything else is part
5669 // of the IP address pool and is already routed, it
5670 // just needs to be added to the IP cache.
5671 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5672 if (session
[s
].ip_pool_index
== -1) // static ip
5674 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5677 cache_ipmap(session
[s
].ip
, s
);
5679 if ((g
= grp_groupbysession(s
)))
5681 grp_setgrouproute(g
, 1);
5682 cluster_send_groupe(g
);
5686 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5687 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5689 // Run the plugin's against this new session.
5691 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5692 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5695 // Allocate TBFs if throttled
5696 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5697 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5699 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5701 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5702 fmtaddr(htonl(session
[s
].ip
), 0),
5703 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5705 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5707 return 1; // RADIUS OK and IP allocated, done...
5711 // This session just got dropped on us by the master or something.
5712 // Make sure our tables up up to date...
5714 int load_session(sessionidt s
, sessiont
*new)
5720 if (new->ip_pool_index
>= MAXIPPOOL
||
5721 new->tunnel
>= MAXTUNNEL
)
5723 LOG(0, s
, 0, "Strange session update received!\n");
5724 // FIXME! What to do here?
5729 // Ok. All sanity checks passed. Now we're committed to
5730 // loading the new session.
5733 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5735 // See if routes/ip cache need updating
5736 if (new->ip
!= session
[s
].ip
)
5739 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5740 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5741 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5749 // remove old routes...
5750 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5752 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5753 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5756 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5762 if (session
[s
].ip_pool_index
== -1) // static IP
5764 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5766 else // It's part of the IP pool, remove it manually.
5767 uncache_ipmap(session
[s
].ip
);
5772 // add new routes...
5773 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5775 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5776 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5779 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5785 // If there's a new one, add it.
5786 if (new->ip_pool_index
== -1)
5788 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5791 cache_ipmap(new->ip
, s
);
5796 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5797 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5800 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5802 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5806 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5808 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5809 new->filter_out
= 0;
5812 if (new->filter_in
!= session
[s
].filter_in
)
5814 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5815 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5818 if (new->filter_out
!= session
[s
].filter_out
)
5820 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5821 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5824 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5825 // for walking the sessions to forward byte counts to the master.
5826 config
->cluster_highest_sessionid
= s
;
5828 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5830 // Do fixups into address pool.
5831 if (new->ip_pool_index
!= -1)
5832 fix_address_pool(s
);
5837 static void initplugins()
5841 loaded_plugins
= ll_init();
5842 // Initialize the plugins to nothing
5843 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5844 plugins
[i
] = ll_init();
5847 static void *open_plugin(char *plugin_name
, int load
)
5849 char path
[256] = "";
5851 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5852 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5853 return dlopen(path
, RTLD_NOW
);
5856 // plugin callback to get a config value
5857 static void *getconfig(char *key
, enum config_typet type
)
5861 for (i
= 0; config_values
[i
].key
; i
++)
5863 if (!strcmp(config_values
[i
].key
, key
))
5865 if (config_values
[i
].type
== type
)
5866 return ((void *) config
) + config_values
[i
].offset
;
5868 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5869 key
, type
, config_values
[i
].type
);
5875 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5879 static int add_plugin(char *plugin_name
)
5881 static struct pluginfuncs funcs
= {
5886 sessiontbysessionidt
,
5887 sessionidtbysessiont
,
5894 cluster_send_session
,
5897 void *p
= open_plugin(plugin_name
, 1);
5898 int (*initfunc
)(struct pluginfuncs
*);
5903 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5907 if (ll_contains(loaded_plugins
, p
))
5910 return 0; // already loaded
5914 int *v
= dlsym(p
, "plugin_api_version");
5915 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5917 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5923 if ((initfunc
= dlsym(p
, "plugin_init")))
5925 if (!initfunc(&funcs
))
5927 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5933 ll_push(loaded_plugins
, p
);
5935 for (i
= 0; i
< max_plugin_functions
; i
++)
5938 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5940 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5941 ll_push(plugins
[i
], x
);
5945 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5949 static void run_plugin_done(void *plugin
)
5951 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5957 static int remove_plugin(char *plugin_name
)
5959 void *p
= open_plugin(plugin_name
, 0);
5965 if (ll_contains(loaded_plugins
, p
))
5968 for (i
= 0; i
< max_plugin_functions
; i
++)
5971 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5972 ll_delete(plugins
[i
], x
);
5975 ll_delete(loaded_plugins
, p
);
5981 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5985 int run_plugins(int plugin_type
, void *data
)
5987 int (*func
)(void *data
);
5989 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5990 return PLUGIN_RET_ERROR
;
5992 ll_reset(plugins
[plugin_type
]);
5993 while ((func
= ll_next(plugins
[plugin_type
])))
5997 if (r
!= PLUGIN_RET_OK
)
5998 return r
; // stop here
6001 return PLUGIN_RET_OK
;
6004 static void plugins_done()
6008 ll_reset(loaded_plugins
);
6009 while ((p
= ll_next(loaded_plugins
)))
6013 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
6015 struct nsctl request
;
6016 struct nsctl response
;
6017 int type
= unpack_control(&request
, buf
, len
);
6021 if (log_stream
&& config
->debug
>= 4)
6025 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6026 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
6030 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6031 dump_control(&request
, log_stream
);
6037 case NSCTL_REQ_LOAD
:
6038 if (request
.argc
!= 1)
6040 response
.type
= NSCTL_RES_ERR
;
6042 response
.argv
[0] = "name of plugin required";
6044 else if ((r
= add_plugin(request
.argv
[0])) < 1)
6046 response
.type
= NSCTL_RES_ERR
;
6048 response
.argv
[0] = !r
6049 ? "plugin already loaded"
6050 : "error loading plugin";
6054 response
.type
= NSCTL_RES_OK
;
6060 case NSCTL_REQ_UNLOAD
:
6061 if (request
.argc
!= 1)
6063 response
.type
= NSCTL_RES_ERR
;
6065 response
.argv
[0] = "name of plugin required";
6067 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
6069 response
.type
= NSCTL_RES_ERR
;
6071 response
.argv
[0] = !r
6072 ? "plugin not loaded"
6073 : "plugin not found";
6077 response
.type
= NSCTL_RES_OK
;
6083 case NSCTL_REQ_HELP
:
6084 response
.type
= NSCTL_RES_OK
;
6087 ll_reset(loaded_plugins
);
6088 while ((p
= ll_next(loaded_plugins
)))
6090 char **help
= dlsym(p
, "plugin_control_help");
6091 while (response
.argc
< 0xff && help
&& *help
)
6092 response
.argv
[response
.argc
++] = *help
++;
6097 case NSCTL_REQ_CONTROL
:
6099 struct param_control param
= {
6100 config
->cluster_iam_master
,
6107 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
6109 if (r
== PLUGIN_RET_ERROR
)
6111 response
.type
= NSCTL_RES_ERR
;
6113 response
.argv
[0] = param
.additional
6115 : "error returned by plugin";
6117 else if (r
== PLUGIN_RET_NOTMASTER
)
6119 static char msg
[] = "must be run on master: 000.000.000.000";
6121 response
.type
= NSCTL_RES_ERR
;
6123 if (config
->cluster_master_address
)
6125 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
6126 response
.argv
[0] = msg
;
6130 response
.argv
[0] = "must be run on master: none elected";
6133 else if (!(param
.response
& NSCTL_RESPONSE
))
6135 response
.type
= NSCTL_RES_ERR
;
6137 response
.argv
[0] = param
.response
6138 ? "unrecognised response value from plugin"
6139 : "unhandled action";
6143 response
.type
= param
.response
;
6145 if (param
.additional
)
6148 response
.argv
[0] = param
.additional
;
6156 response
.type
= NSCTL_RES_ERR
;
6158 response
.argv
[0] = "error unpacking control packet";
6161 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6164 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6168 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6171 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6172 if (log_stream
&& config
->debug
>= 4)
6174 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6175 dump_control(&response
, log_stream
);
6179 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6180 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6185 static tunnelidt
new_tunnel()
6188 for (i
= 1; i
< MAXTUNNEL
; i
++)
6190 if ((tunnel
[i
].state
== TUNNELFREE
) && (i
!= TUNNEL_ID_PPPOE
))
6192 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6193 if (i
> config
->cluster_highest_tunnelid
)
6194 config
->cluster_highest_tunnelid
= i
;
6198 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6203 // We're becoming the master. Do any required setup..
6205 // This is principally telling all the plugins that we're
6206 // now a master, and telling them about all the sessions
6207 // that are active too..
6209 void become_master(void)
6212 static struct event_data d
[RADIUS_FDS
];
6213 struct epoll_event e
;
6215 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6217 // running a bunch of iptables commands is slow and can cause
6218 // the master to drop tunnels on takeover--kludge around the
6219 // problem by forking for the moment (note: race)
6220 if (!fork_and_close())
6222 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6224 if (!session
[s
].opened
) // Not an in-use session.
6227 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6234 for (i
= 0; i
< RADIUS_FDS
; i
++)
6236 d
[i
].type
= FD_TYPE_RADIUS
;
6240 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6244 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6250 if (CLI_HELP_REQUESTED
)
6251 return CLI_HELP_NO_ARGS
;
6254 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6256 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6259 if (!session
[s
].opened
)
6262 idle
= time_now
- session
[s
].last_data
;
6263 idle
/= 5 ; // In multiples of 5 seconds.
6273 for (i
= 0; i
< 63; ++i
)
6275 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6277 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6278 cli_print(cli
, "%d total sessions open.", count
);
6282 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6288 if (CLI_HELP_REQUESTED
)
6289 return CLI_HELP_NO_ARGS
;
6292 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6294 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6297 if (!session
[s
].opened
)
6300 d
= time_now
- session
[s
].opened
;
6303 while (d
> 1 && open
< 32)
6313 for (i
= 0; i
< 30; ++i
)
6315 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6318 cli_print(cli
, "%d total sessions open.", count
);
6324 * This unencodes the AVP using the L2TP secret and the previously
6325 * stored random vector. It overwrites the hidden data with the
6326 * unhidden AVP subformat.
6328 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6334 uint16_t m
= htons(type
);
6336 // Compute initial pad
6338 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6339 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6340 MD5_Update(&ctx
, vector
, vec_len
);
6341 MD5_Final(digest
, &ctx
);
6343 // pointer to last decoded 16 octets
6348 // calculate a new pad based on the last decoded block
6349 if (d
>= sizeof(digest
))
6352 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6353 MD5_Update(&ctx
, last
, sizeof(digest
));
6354 MD5_Final(digest
, &ctx
);
6360 *value
++ ^= digest
[d
++];
6365 int find_filter(char const *name
, size_t len
)
6370 for (i
= 0; i
< MAXFILTER
; i
++)
6372 if (!*ip_filters
[i
].name
)
6380 if (strlen(ip_filters
[i
].name
) != len
)
6383 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6390 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6394 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6395 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6396 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6397 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6398 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6404 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6408 case FILTER_FLAG_OP_ANY
:
6409 return (flags
& sflags
) || (~flags
& cflags
);
6411 case FILTER_FLAG_OP_ALL
:
6412 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6414 case FILTER_FLAG_OP_EST
:
6415 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6421 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6423 uint16_t frag_offset
;
6427 uint16_t src_port
= 0;
6428 uint16_t dst_port
= 0;
6430 ip_filter_rulet
*rule
;
6432 if (len
< 20) // up to end of destination address
6435 if ((*buf
>> 4) != 4) // IPv4
6438 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6440 src_ip
= *(in_addr_t
*) (buf
+ 12);
6441 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6443 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6445 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6446 if (len
< l
+ 4) // ports
6449 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6450 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6451 if (proto
== IPPROTO_TCP
)
6453 if (len
< l
+ 14) // flags
6456 flags
= buf
[l
+ 13] & 0x3f;
6460 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6462 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6465 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6466 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6469 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6470 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6475 // layer 4 deny rules are skipped
6476 if (rule
->action
== FILTER_ACTION_DENY
&&
6477 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6485 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6487 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6490 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6493 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6494 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6501 return rule
->action
== FILTER_ACTION_PERMIT
;
6508 tunnelidt
lac_new_tunnel()
6510 return new_tunnel();
6513 void lac_tunnelclear(tunnelidt t
)
6518 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6520 uint16_t version
= 0x0100; // protocol version
6522 tunnel
[t
].state
= TUNNELOPENING
;
6524 // Sent SCCRQ - Start Control Connection Request
6525 controlt
*c
= controlnew(1); // sending SCCRQ
6526 controls(c
, 7, hostname
, 1); // host name
6527 controls(c
, 8, Vendor_name
, 1); // Vendor name
6528 control16(c
, 2, version
, 1); // protocol version
6529 control32(c
, 3, 3, 1); // framing Capabilities
6530 control16(c
, 9, t
, 1); // assigned tunnel
6531 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6532 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6533 controladd(c
, 0, t
); // send
6536 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6538 // Sent ICRQ Incoming-call-request
6539 controlt
*c
= controlnew(10); // ICRQ
6541 control16(c
, 14, s
, 1); // assigned sesion
6542 call_serial_number
++;
6543 control32(c
, 15, call_serial_number
, 1); // call serial number
6544 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6545 controladd(c
, 0, t
); // send
6548 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6550 tunnelshutdown(t
, reason
, result
, error
, msg
);