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
;
1397 sp
->coutgrp_delta
+= len
;
1399 sp
->last_data
= time_now
;
1401 sess_local
[s
].cout
+= len
; // To send to master..
1402 sess_local
[s
].pout
++;
1405 // process outgoing (to tunnel) IP
1407 // (i.e. this routine writes to data[-8]).
1408 void processipout(uint8_t *buf
, int len
)
1416 uint8_t *data
= buf
; // Keep a copy of the originals.
1419 uint8_t fragbuf
[MAXETHER
+ 20];
1421 CSTAT(processipout
);
1423 if (len
< MIN_IP_SIZE
)
1425 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1426 STAT(tun_rx_errors
);
1429 if (len
>= MAXETHER
)
1431 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1432 STAT(tun_rx_errors
);
1436 // Skip the tun header
1440 // Got an IP header now
1441 if (*(uint8_t *)(buf
) >> 4 != 4)
1443 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1447 ip
= *(uint32_t *)(buf
+ 16);
1448 if ((g
= grp_groupbyip(ip
)))
1450 s
= grp_getnextsession(g
, ip
);
1453 // Is this a packet for a session that doesn't exist?
1454 static int rate
= 0; // Number of ICMP packets we've sent this second.
1455 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1457 if (last
!= time_now
)
1463 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1465 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1466 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1467 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1472 else if (!(s
= sessionbyip(ip
)))
1474 // Is this a packet for a session that doesn't exist?
1475 static int rate
= 0; // Number of ICMP packets we've sent this second.
1476 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1478 if (last
!= time_now
)
1484 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1486 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1487 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1488 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1493 t
= session
[s
].tunnel
;
1494 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1496 LOG(3, s
, t
, "Packet size more than session MRU\n");
1502 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1503 if (config
->max_packets
> 0)
1505 if (sess_local
[s
].last_packet_out
== TIME
)
1507 int max
= config
->max_packets
;
1509 // All packets for throttled sessions are handled by the
1510 // master, so further limit by using the throttle rate.
1511 // A bit of a kludge, since throttle rate is in kbps,
1512 // but should still be generous given our average DSL
1513 // packet size is 200 bytes: a limit of 28kbps equates
1514 // to around 180 packets per second.
1515 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1516 max
= sp
->throttle_out
;
1518 if (++sess_local
[s
].packets_out
> max
)
1520 sess_local
[s
].packets_dropped
++;
1526 if (sess_local
[s
].packets_dropped
)
1528 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1529 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1530 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1531 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1535 sess_local
[s
].last_packet_out
= TIME
;
1536 sess_local
[s
].packets_out
= 1;
1537 sess_local
[s
].packets_dropped
= 0;
1541 // run access-list if any
1542 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1545 // adjust MSS on SYN and SYN,ACK packets with options
1546 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1548 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1549 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1550 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1555 // Are we throttling this session?
1556 if (config
->cluster_iam_master
)
1557 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1559 master_throttle_packet(sp
->tbf_out
, data
, size
);
1563 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1565 // We are walled-gardening this
1566 master_garden_packet(s
, data
, size
);
1570 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1573 if (!config
->cluster_iam_master
)
1575 // The MPPP packets must be managed by the Master.
1576 master_forward_mppp_packet(s
, data
, size
);
1580 // Add on L2TP header
1581 sessionidt members
[MAXBUNDLESES
];
1582 bundleidt bid
= session
[s
].bundle
;
1583 bundlet
*b
= &bundle
[bid
];
1584 uint32_t num_of_links
, nb_opened
;
1587 num_of_links
= b
->num_of_links
;
1589 for (i
= 0;i
< num_of_links
;i
++)
1592 if (session
[s
].ppp
.lcp
== Opened
)
1594 members
[nb_opened
] = s
;
1601 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1605 num_of_links
= nb_opened
;
1606 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1607 s
= members
[b
->current_ses
];
1608 t
= session
[s
].tunnel
;
1610 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1612 if (num_of_links
> 1)
1614 if(len
> MINFRAGLEN
)
1616 //for rotate traffic among the member links
1617 uint32_t divisor
= num_of_links
;
1619 divisor
= divisor
/2 + (divisor
& 1);
1621 // Partition the packet to "num_of_links" fragments
1622 uint32_t fraglen
= len
/ divisor
;
1623 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1624 uint32_t remain
= len
;
1626 // send the first packet
1627 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1629 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1632 update_session_out_stat(s
, sp
, fraglen
);
1635 while (remain
> last_fraglen
)
1637 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1638 s
= members
[b
->current_ses
];
1639 t
= session
[s
].tunnel
;
1641 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1642 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1644 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1645 update_session_out_stat(s
, sp
, fraglen
);
1648 // send the last fragment
1649 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1650 s
= members
[b
->current_ses
];
1651 t
= session
[s
].tunnel
;
1653 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1654 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1656 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1657 update_session_out_stat(s
, sp
, remain
);
1658 if (remain
!= last_fraglen
)
1659 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1663 // Send it as one frame
1664 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1666 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1667 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1668 update_session_out_stat(s
, sp
, len
);
1673 // Send it as one frame (NO MPPP Frame)
1674 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1675 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1676 update_session_out_stat(s
, sp
, len
);
1681 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1682 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1683 update_session_out_stat(s
, sp
, len
);
1686 // Snooping this session, send it to intercept box
1687 if (sp
->snoop_ip
&& sp
->snoop_port
)
1688 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1693 // process outgoing (to tunnel) IPv6
1695 static void processipv6out(uint8_t * buf
, int len
)
1701 struct in6_addr ip6
;
1703 uint8_t *data
= buf
; // Keep a copy of the originals.
1706 uint8_t b
[MAXETHER
+ 20];
1708 CSTAT(processipv6out
);
1710 if (len
< MIN_IP_SIZE
)
1712 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1713 STAT(tunnel_tx_errors
);
1716 if (len
>= MAXETHER
)
1718 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1719 STAT(tunnel_tx_errors
);
1723 // Skip the tun header
1727 // Got an IP header now
1728 if (*(uint8_t *)(buf
) >> 4 != 6)
1730 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1734 ip6
= *(struct in6_addr
*)(buf
+24);
1735 s
= sessionbyipv6(ip6
);
1739 ip
= *(uint32_t *)(buf
+ 32);
1740 s
= sessionbyip(ip
);
1745 // Is this a packet for a session that doesn't exist?
1746 static int rate
= 0; // Number of ICMP packets we've sent this second.
1747 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1749 if (last
!= time_now
)
1755 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1757 // FIXME: Should send icmp6 host unreachable
1761 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1763 bundleidt bid
= session
[s
].bundle
;
1764 bundlet
*b
= &bundle
[bid
];
1766 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1767 s
= b
->members
[b
->current_ses
];
1768 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1770 t
= session
[s
].tunnel
;
1772 sp
->last_data
= time_now
;
1774 // FIXME: add DoS prevention/filters?
1778 // Are we throttling this session?
1779 if (config
->cluster_iam_master
)
1780 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1782 master_throttle_packet(sp
->tbf_out
, data
, size
);
1785 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1787 // We are walled-gardening this
1788 master_garden_packet(s
, data
, size
);
1792 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1794 // Add on L2TP header
1796 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1798 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1801 // Snooping this session, send it to intercept box
1802 if (sp
->snoop_ip
&& sp
->snoop_port
)
1803 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1805 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1806 sp
->cout_delta
+= len
;
1807 sp
->coutgrp_delta
+= len
;
1811 sess_local
[s
].cout
+= len
; // To send to master..
1812 sess_local
[s
].pout
++;
1816 // Helper routine for the TBF filters.
1817 // Used to send queued data in to the user!
1819 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1824 uint8_t b
[MAXETHER
+ 20];
1826 if (len
< 0 || len
> MAXETHER
)
1828 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1832 // Skip the tun header
1839 t
= session
[s
].tunnel
;
1842 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1844 // Add on L2TP header
1846 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1848 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1851 // Snooping this session.
1852 if (sp
->snoop_ip
&& sp
->snoop_port
)
1853 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1855 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1856 sp
->cout_delta
+= len
;
1857 sp
->coutgrp_delta
+= len
;
1861 sess_local
[s
].cout
+= len
; // To send to master..
1862 sess_local
[s
].pout
++;
1865 // add an AVP (16 bit)
1866 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1868 uint16_t l
= (m
? 0x8008 : 0x0008);
1869 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1870 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1871 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1872 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1876 // add an AVP (32 bit)
1877 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1879 uint16_t l
= (m
? 0x800A : 0x000A);
1880 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1881 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1882 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1883 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1887 // add an AVP (string)
1888 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1890 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1891 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1892 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1893 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1894 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1895 c
->length
+= 6 + strlen(val
);
1899 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1901 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1902 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1903 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1904 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1905 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1906 c
->length
+= 6 + len
;
1909 // new control connection
1910 static controlt
*controlnew(uint16_t mtype
)
1914 c
= malloc(sizeof(controlt
));
1918 controlfree
= c
->next
;
1922 c
->buf
[0] = 0xC8; // flags
1923 c
->buf
[1] = 0x02; // ver
1925 control16(c
, 0, mtype
, 1);
1929 // send zero block if nothing is waiting
1931 static void controlnull(tunnelidt t
)
1934 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1937 buf
[0] = htons(0xC802); // flags/ver
1938 buf
[1] = htons(12); // length
1939 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1940 buf
[3] = htons(0); // session
1941 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1942 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1943 tunnelsend((uint8_t *)buf
, 12, t
);
1946 // add a control message to a tunnel, and send if within window
1947 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1949 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1950 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1951 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1952 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1953 tunnel
[t
].ns
++; // advance sequence
1954 // link in message in to queue
1955 if (tunnel
[t
].controlc
)
1956 tunnel
[t
].controle
->next
= c
;
1958 tunnel
[t
].controls
= c
;
1960 tunnel
[t
].controle
= c
;
1961 tunnel
[t
].controlc
++;
1963 // send now if space in window
1964 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1966 tunnel
[t
].try = 0; // first send
1967 tunnelsend(c
->buf
, c
->length
, t
);
1972 // Throttle or Unthrottle a session
1974 // Throttle the data from/to through a session to no more than
1975 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1978 // If either value is -1, the current value is retained for that
1981 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1983 if (!session
[s
].opened
)
1984 return; // No-one home.
1986 if (!*session
[s
].user
)
1987 return; // User not logged in
1991 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1992 if (session
[s
].tbf_in
)
1993 free_tbf(session
[s
].tbf_in
);
1996 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1998 session
[s
].tbf_in
= 0;
2000 session
[s
].throttle_in
= rate_in
;
2005 int bytes
= rate_out
* 1024 / 8;
2006 if (session
[s
].tbf_out
)
2007 free_tbf(session
[s
].tbf_out
);
2010 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
2012 session
[s
].tbf_out
= 0;
2014 session
[s
].throttle_out
= rate_out
;
2018 // add/remove filters from session (-1 = no change)
2019 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
2021 if (!session
[s
].opened
)
2022 return; // No-one home.
2024 if (!*session
[s
].user
)
2025 return; // User not logged in
2028 if (filter_in
> MAXFILTER
) filter_in
= -1;
2029 if (filter_out
> MAXFILTER
) filter_out
= -1;
2030 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
2031 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
2035 if (session
[s
].filter_in
)
2036 ip_filters
[session
[s
].filter_in
- 1].used
--;
2039 ip_filters
[filter_in
- 1].used
++;
2041 session
[s
].filter_in
= filter_in
;
2044 if (filter_out
>= 0)
2046 if (session
[s
].filter_out
)
2047 ip_filters
[session
[s
].filter_out
- 1].used
--;
2050 ip_filters
[filter_out
- 1].used
++;
2052 session
[s
].filter_out
= filter_out
;
2056 // start tidy shutdown of session
2057 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
2059 int walled_garden
= session
[s
].walled_garden
;
2060 bundleidt b
= session
[s
].bundle
;
2061 //delete routes only for last session in bundle (in case of MPPP)
2062 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
2064 CSTAT(sessionshutdown
);
2066 if (!session
[s
].opened
)
2068 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2069 return; // not a live session
2072 if (!session
[s
].die
)
2074 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2075 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2076 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2079 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2081 // RADIUS Stop message
2082 uint16_t r
= radiusnew(s
);
2085 // stop, if not already trying
2086 if (radius
[r
].state
!= RADIUSSTOP
)
2088 radius
[r
].term_cause
= term_cause
;
2089 radius
[r
].term_msg
= reason
;
2090 radiussend(r
, RADIUSSTOP
);
2094 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2096 // Save counters to dump to accounting file
2097 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2098 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2101 if (!session
[s
].die
)
2102 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2105 { // IP allocated, clear and unroute
2108 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2110 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2111 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2114 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2115 session
[s
].route
[r
].ip
= 0;
2118 if (session
[s
].ip_pool_index
== -1) // static ip
2120 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2126 // unroute IPv6, if setup
2127 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
2128 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2132 // This session was part of a bundle
2133 bundle
[b
].num_of_links
--;
2134 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2135 if(bundle
[b
].num_of_links
== 0)
2138 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2142 // Adjust the members array to accomodate the new change
2143 uint8_t mem_num
= 0;
2144 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2145 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2148 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2149 if(bundle
[b
].members
[ml
] == s
)
2154 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2155 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2157 // If the killed session is the first of the bundle,
2158 // the new first session must be stored in the cache_ipmap
2159 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2162 sessionidt new_s
= bundle
[b
].members
[0];
2165 // Add the route for this session.
2166 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2171 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2172 ip
= session
[new_s
].route
[r
].ip
;
2174 if (!prefixlen
) prefixlen
= 32;
2175 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2177 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2178 cache_ipmap(i
, new_s
);
2180 cache_ipmap(session
[new_s
].ip
, new_s
);
2183 if (session
[new_s
].ipv6prefixlen
)
2184 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2189 cluster_send_bundle(b
);
2193 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2194 throttle_session(s
, 0, 0);
2198 if (session
[s
].tunnel
== TUNNEL_ID_PPPOE
)
2200 pppoe_shutdown_session(s
);
2205 controlt
*c
= controlnew(14); // sending CDN
2209 buf
[0] = htons(cdn_result
);
2210 buf
[1] = htons(cdn_error
);
2211 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2214 control16(c
, 1, cdn_result
, 1);
2216 control16(c
, 14, s
, 1); // assigned session (our end)
2217 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2221 // update filter refcounts
2222 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2223 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2226 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2227 sess_local
[s
].lcp
.restart
= 0;
2228 sess_local
[s
].ipcp
.restart
= 0;
2229 sess_local
[s
].ipv6cp
.restart
= 0;
2230 sess_local
[s
].ccp
.restart
= 0;
2232 cluster_send_session(s
);
2235 void sendipcp(sessionidt s
, tunnelidt t
)
2237 uint8_t buf
[MAXETHER
];
2241 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2243 if (!session
[s
].unique_id
)
2245 if (!++last_id
) ++last_id
; // skip zero
2246 session
[s
].unique_id
= last_id
;
2249 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2253 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2254 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2255 q
[4] = 3; // ip address option
2256 q
[5] = 6; // option length
2257 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2258 config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] :
2259 my_address
; // send my IP
2261 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2262 restart_timer(s
, ipcp
);
2265 void sendipv6cp(sessionidt s
, tunnelidt t
)
2267 uint8_t buf
[MAXETHER
];
2271 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2273 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2277 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2278 // only send one type
2280 *(uint16_t *) (q
+ 2) = htons(14);
2281 q
[4] = 1; // interface identifier option
2282 q
[5] = 10; // option length
2283 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2284 *(uint32_t *) (q
+ 10) = 0;
2287 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2288 restart_timer(s
, ipv6cp
);
2291 static void sessionclear(sessionidt s
)
2293 memset(&session
[s
], 0, sizeof(session
[s
]));
2294 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2295 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2297 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2298 session
[s
].next
= sessionfree
;
2302 // kill a session now
2303 void sessionkill(sessionidt s
, char *reason
)
2309 if (!session
[s
].opened
) // not alive
2312 if (session
[s
].next
)
2314 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2318 if (!session
[s
].die
)
2319 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2321 if (sess_local
[s
].radius
)
2322 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2324 if (session
[s
].forwardtosession
)
2326 sessionidt sess
= session
[s
].forwardtosession
;
2327 if (session
[sess
].forwardtosession
== s
)
2329 // Shutdown the linked session also.
2330 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2334 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2336 if ((g
= grp_groupbysession(s
)))
2338 grp_removesession(g
, s
);
2342 cluster_send_session(s
);
2345 static void tunnelclear(tunnelidt t
)
2348 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2349 tunnel
[t
].state
= TUNNELFREE
;
2352 static void bundleclear(bundleidt b
)
2355 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2356 bundle
[b
].state
= BUNDLEFREE
;
2359 // kill a tunnel now
2360 static void tunnelkill(tunnelidt t
, char *reason
)
2367 tunnel
[t
].state
= TUNNELDIE
;
2369 // free control messages
2370 while ((c
= tunnel
[t
].controls
))
2372 controlt
* n
= c
->next
;
2373 tunnel
[t
].controls
= n
;
2374 tunnel
[t
].controlc
--;
2375 c
->next
= controlfree
;
2379 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2380 if (session
[s
].tunnel
== t
)
2381 sessionkill(s
, reason
);
2385 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2386 cli_tunnel_actions
[t
].action
= 0;
2387 cluster_send_tunnel(t
);
2390 // shut down a tunnel cleanly
2391 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2395 CSTAT(tunnelshutdown
);
2397 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2399 // never set up, can immediately kill
2400 tunnelkill(t
, reason
);
2403 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2406 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2407 if (session
[s
].tunnel
== t
)
2408 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2410 tunnel
[t
].state
= TUNNELDIE
;
2411 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2412 cluster_send_tunnel(t
);
2413 // TBA - should we wait for sessions to stop?
2416 controlt
*c
= controlnew(4); // sending StopCCN
2421 buf
[0] = htons(result
);
2422 buf
[1] = htons(error
);
2425 int m
= strlen(msg
);
2426 if (m
+ 4 > sizeof(buf
))
2427 m
= sizeof(buf
) - 4;
2429 memcpy(buf
+2, msg
, m
);
2433 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2436 control16(c
, 1, result
, 1);
2438 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2439 controladd(c
, 0, t
); // send the message
2443 // read and process packet on tunnel (UDP)
2444 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, uint16_t indexudpfd
)
2446 uint8_t *chapresponse
= NULL
;
2447 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2448 uint8_t *p
= buf
+ 2;
2455 LOG_HEX(5, "UDP Data", buf
, len
);
2456 STAT(tunnel_rx_packets
);
2457 INC_STAT(tunnel_rx_bytes
, len
);
2460 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2461 STAT(tunnel_rx_errors
);
2464 if ((buf
[1] & 0x0F) != 2)
2466 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2467 STAT(tunnel_rx_errors
);
2472 l
= ntohs(*(uint16_t *) p
);
2475 t
= ntohs(*(uint16_t *) p
);
2477 s
= ntohs(*(uint16_t *) p
);
2479 if (s
>= MAXSESSION
)
2481 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2482 STAT(tunnel_rx_errors
);
2487 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2488 STAT(tunnel_rx_errors
);
2491 if (t
== TUNNEL_ID_PPPOE
)
2493 LOG(1, s
, t
, "Received UDP packet with tunnel ID reserved for pppoe\n");
2494 STAT(tunnel_rx_errors
);
2499 ns
= ntohs(*(uint16_t *) p
);
2501 nr
= ntohs(*(uint16_t *) p
);
2506 uint16_t o
= ntohs(*(uint16_t *) p
);
2511 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2512 STAT(tunnel_rx_errors
);
2517 // used to time out old tunnels
2518 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2519 tunnel
[t
].lastrec
= time_now
;
2523 uint16_t message
= 0xFFFF; // message type
2525 uint8_t mandatory
= 0;
2526 uint16_t asession
= 0; // assigned session
2527 uint32_t amagic
= 0; // magic number
2528 uint8_t aflags
= 0; // flags from last LCF
2529 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2530 char called
[MAXTEL
] = ""; // called number
2531 char calling
[MAXTEL
] = ""; // calling number
2533 if (!config
->cluster_iam_master
)
2535 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
2539 // control messages must have bits 0x80|0x40|0x08
2540 // (type, length and sequence) set, and bits 0x02|0x01
2541 // (offset and priority) clear
2542 if ((*buf
& 0xCB) != 0xC8)
2544 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2545 STAT(tunnel_rx_errors
);
2549 // check for duplicate tunnel open message
2555 // Is this a duplicate of the first packet? (SCCRQ)
2557 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2559 if (tunnel
[i
].state
!= TUNNELOPENING
||
2560 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2561 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2564 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2569 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2570 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2572 // if no tunnel specified, assign one
2575 if (!(t
= new_tunnel()))
2577 LOG(1, 0, 0, "No more tunnels\n");
2578 STAT(tunnel_overflow
);
2582 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2583 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2584 tunnel
[t
].window
= 4; // default window
2585 tunnel
[t
].indexudp
= indexudpfd
;
2586 STAT(tunnel_created
);
2587 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2588 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2591 // If the 'ns' just received is not the 'nr' we're
2592 // expecting, just send an ack and drop it.
2594 // if 'ns' is less, then we got a retransmitted packet.
2595 // if 'ns' is greater than missed a packet. Either way
2596 // we should ignore it.
2597 if (ns
!= tunnel
[t
].nr
)
2599 // is this the sequence we were expecting?
2600 STAT(tunnel_rx_errors
);
2601 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2602 t
, ns
, tunnel
[t
].nr
);
2604 if (l
) // Is this not a ZLB?
2609 // check sequence of this message
2611 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2612 // some to clear maybe?
2613 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2615 controlt
*c
= tunnel
[t
].controls
;
2616 tunnel
[t
].controls
= c
->next
;
2617 tunnel
[t
].controlc
--;
2618 c
->next
= controlfree
;
2621 tunnel
[t
].try = 0; // we have progress
2624 // receiver advance (do here so quoted correctly in any sends below)
2625 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2626 if (skip
< 0) skip
= 0;
2627 if (skip
< tunnel
[t
].controlc
)
2629 // some control packets can now be sent that were previous stuck out of window
2630 int tosend
= tunnel
[t
].window
- skip
;
2631 controlt
*c
= tunnel
[t
].controls
;
2639 tunnel
[t
].try = 0; // first send
2640 tunnelsend(c
->buf
, c
->length
, t
);
2645 if (!tunnel
[t
].controlc
)
2646 tunnel
[t
].retry
= 0; // caught up
2649 { // if not a null message
2654 // Default disconnect cause/message on receipt of CDN. Set to
2655 // more specific value from attribute 1 (result code) or 46
2656 // (disconnect cause) if present below.
2657 int disc_cause_set
= 0;
2658 int disc_cause
= TERM_NAS_REQUEST
;
2659 char const *disc_reason
= "Closed (Received CDN).";
2662 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2664 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2671 LOG(1, s
, t
, "Invalid length in AVP\n");
2672 STAT(tunnel_rx_errors
);
2677 if (flags
& 0x3C) // reserved bits, should be clear
2679 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2681 result
= 2; // general error
2682 error
= 3; // reserved field non-zero
2687 if (*(uint16_t *) (b
))
2689 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2691 result
= 2; // general error
2692 error
= 6; // generic vendor-specific error
2693 msg
= "unsupported vendor-specific";
2697 mtype
= ntohs(*(uint16_t *) (b
));
2705 // handle hidden AVPs
2706 if (!*config
->l2tp_secret
)
2708 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2710 result
= 2; // general error
2711 error
= 6; // generic vendor-specific error
2712 msg
= "secret not specified";
2715 if (!session
[s
].random_vector_length
)
2717 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2719 result
= 2; // general error
2720 error
= 6; // generic
2721 msg
= "no random vector";
2726 LOG(2, s
, t
, "Short hidden AVP.\n");
2728 result
= 2; // general error
2729 error
= 2; // length is wrong
2735 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2737 orig_len
= ntohs(*(uint16_t *) b
);
2738 if (orig_len
> n
+ 2)
2740 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2744 result
= 2; // general error
2745 error
= 2; // length is wrong
2754 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2755 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2759 case 0: // message type
2760 message
= ntohs(*(uint16_t *) b
);
2761 mandatory
= flags
& 0x80;
2762 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2764 case 1: // result code
2766 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2767 char const *resdesc
= "(unknown)";
2768 char const *errdesc
= NULL
;
2773 resdesc
= l2tp_stopccn_result_code(rescode
);
2774 cause
= TERM_LOST_SERVICE
;
2776 else if (message
== 14)
2778 resdesc
= l2tp_cdn_result_code(rescode
);
2780 cause
= TERM_LOST_CARRIER
;
2782 cause
= TERM_ADMIN_RESET
;
2785 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2788 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2789 errdesc
= l2tp_error_code(errcode
);
2790 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2793 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2795 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2797 disc_cause_set
= mtype
;
2798 disc_reason
= errdesc
? errdesc
: resdesc
;
2805 case 2: // protocol version
2807 version
= ntohs(*(uint16_t *) (b
));
2808 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2809 if (version
&& version
!= 0x0100)
2810 { // allow 0.0 and 1.0
2811 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2813 result
= 5; // unspported protocol version
2814 error
= 0x0100; // supported version
2820 case 3: // framing capabilities
2822 case 4: // bearer capabilities
2824 case 5: // tie breaker
2825 // We never open tunnels, so we don't care about tie breakers
2827 case 6: // firmware revision
2829 case 7: // host name
2830 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2831 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2832 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2833 // TBA - to send to RADIUS
2835 case 8: // vendor name
2836 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2837 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2838 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2840 case 9: // assigned tunnel
2841 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2842 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2844 case 10: // rx window
2845 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2846 if (!tunnel
[t
].window
)
2847 tunnel
[t
].window
= 1; // window of 0 is silly
2848 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2850 case 11: // Challenge
2852 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2853 build_chap_response(b
, 2, n
, &chapresponse
);
2856 case 13: // Response
2857 if (tunnel
[t
].isremotelns
)
2859 chapresponse
= calloc(17, 1);
2860 memcpy(chapresponse
, b
, (n
< 17) ? n
: 16);
2861 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2864 // Why did they send a response? We never challenge.
2865 LOG(2, s
, t
, " received unexpected challenge response\n");
2868 case 14: // assigned session
2869 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2870 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2872 case 15: // call serial number
2873 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2875 case 18: // bearer type
2876 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2879 case 19: // framing type
2880 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2883 case 21: // called number
2884 memset(called
, 0, sizeof(called
));
2885 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2886 LOG(4, s
, t
, " Called <%s>\n", called
);
2888 case 22: // calling number
2889 memset(calling
, 0, sizeof(calling
));
2890 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2891 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2895 case 24: // tx connect speed
2898 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2902 // AS5300s send connect speed as a string
2904 memset(tmp
, 0, sizeof(tmp
));
2905 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2906 session
[s
].tx_connect_speed
= atol(tmp
);
2908 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2910 case 38: // rx connect speed
2913 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2917 // AS5300s send connect speed as a string
2919 memset(tmp
, 0, sizeof(tmp
));
2920 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2921 session
[s
].rx_connect_speed
= atol(tmp
);
2923 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2925 case 25: // Physical Channel ID
2927 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2928 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2931 case 29: // Proxy Authentication Type
2933 uint16_t atype
= ntohs(*(uint16_t *)b
);
2934 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2937 case 30: // Proxy Authentication Name
2940 memset(authname
, 0, sizeof(authname
));
2941 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2942 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2946 case 31: // Proxy Authentication Challenge
2948 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2951 case 32: // Proxy Authentication ID
2953 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2954 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2957 case 33: // Proxy Authentication Response
2958 LOG(4, s
, t
, " Proxy Auth Response\n");
2960 case 27: // last sent lcp
2961 { // find magic number
2962 uint8_t *p
= b
, *e
= p
+ n
;
2963 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2965 if (*p
== 5 && p
[1] == 6) // Magic-Number
2966 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2967 else if (*p
== 7) // Protocol-Field-Compression
2968 aflags
|= SESSION_PFC
;
2969 else if (*p
== 8) // Address-and-Control-Field-Compression
2970 aflags
|= SESSION_ACFC
;
2975 case 28: // last recv lcp confreq
2977 case 26: // Initial Received LCP CONFREQ
2979 case 39: // seq required - we control it as an LNS anyway...
2981 case 36: // Random Vector
2982 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2983 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2984 if (n
> sizeof(session
[s
].random_vector
))
2985 n
= sizeof(session
[s
].random_vector
);
2986 memcpy(session
[s
].random_vector
, b
, n
);
2987 session
[s
].random_vector_length
= n
;
2989 case 46: // ppp disconnect cause
2992 uint16_t code
= ntohs(*(uint16_t *) b
);
2993 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2994 uint8_t dir
= *(b
+ 4);
2996 LOG(4, s
, t
, " PPP disconnect cause "
2997 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2998 code
, proto
, dir
, n
- 5, b
+ 5);
3000 disc_cause_set
= mtype
;
3004 case 1: // admin disconnect
3005 disc_cause
= TERM_ADMIN_RESET
;
3006 disc_reason
= "Administrative disconnect";
3008 case 3: // lcp terminate
3009 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
3010 disc_cause
= TERM_USER_REQUEST
;
3011 disc_reason
= "Normal disconnection";
3013 case 4: // compulsory encryption unavailable
3014 if (dir
!= 1) break; // 1=refused by peer, 2=local
3015 disc_cause
= TERM_USER_ERROR
;
3016 disc_reason
= "Compulsory encryption refused";
3018 case 5: // lcp: fsm timeout
3019 disc_cause
= TERM_PORT_ERROR
;
3020 disc_reason
= "LCP: FSM timeout";
3022 case 6: // lcp: no recognisable lcp packets received
3023 disc_cause
= TERM_PORT_ERROR
;
3024 disc_reason
= "LCP: no recognisable LCP packets";
3026 case 7: // lcp: magic-no error (possibly looped back)
3027 disc_cause
= TERM_PORT_ERROR
;
3028 disc_reason
= "LCP: magic-no error (possible loop)";
3030 case 8: // lcp: echo request timeout
3031 disc_cause
= TERM_PORT_ERROR
;
3032 disc_reason
= "LCP: echo request timeout";
3034 case 13: // auth: fsm timeout
3035 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3036 disc_reason
= "Authentication: FSM timeout";
3038 case 15: // auth: unacceptable auth protocol
3039 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3040 disc_reason
= "Unacceptable authentication protocol";
3042 case 16: // auth: authentication failed
3043 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3044 disc_reason
= "Authentication failed";
3046 case 17: // ncp: fsm timeout
3047 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3048 disc_reason
= "NCP: FSM timeout";
3050 case 18: // ncp: no ncps available
3051 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3052 disc_reason
= "NCP: no NCPs available";
3054 case 19: // ncp: failure to converge on acceptable address
3055 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3056 disc_reason
= (dir
== 1)
3057 ? "NCP: too many Configure-Naks received from peer"
3058 : "NCP: too many Configure-Naks sent to peer";
3060 case 20: // ncp: user not permitted to use any address
3061 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3062 disc_reason
= (dir
== 1)
3063 ? "NCP: local link address not acceptable to peer"
3064 : "NCP: remote link address not acceptable";
3071 static char e
[] = "unknown AVP 0xXXXX";
3072 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
3074 result
= 2; // general error
3075 error
= 8; // unknown mandatory AVP
3076 sprintf((msg
= e
) + 14, "%04x", mtype
);
3083 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3087 case 1: // SCCRQ - Start Control Connection Request
3088 tunnel
[t
].state
= TUNNELOPENING
;
3089 LOG(3, s
, t
, "Received SCCRQ\n");
3090 if (main_quit
!= QUIT_SHUTDOWN
)
3092 LOG(3, s
, t
, "sending SCCRP\n");
3093 controlt
*c
= controlnew(2); // sending SCCRP
3094 control16(c
, 2, version
, 1); // protocol version
3095 control32(c
, 3, 3, 1); // framing
3096 controls(c
, 7, hostname
, 1); // host name
3097 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
3098 control16(c
, 9, t
, 1); // assigned tunnel
3099 controladd(c
, 0, t
); // send the resply
3103 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3107 tunnel
[t
].state
= TUNNELOPEN
;
3108 tunnel
[t
].lastrec
= time_now
;
3109 LOG(3, s
, t
, "Received SCCRP\n");
3110 if (main_quit
!= QUIT_SHUTDOWN
)
3112 if (tunnel
[t
].isremotelns
&& chapresponse
)
3116 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3117 // check authenticator
3118 if (memcmp(hash
, chapresponse
, 16) == 0)
3120 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3121 controlt
*c
= controlnew(3); // sending SCCCN
3122 controls(c
, 7, hostname
, 1); // host name
3123 controls(c
, 8, Vendor_name
, 1); // Vendor name
3124 control16(c
, 2, version
, 1); // protocol version
3125 control32(c
, 3, 3, 1); // framing Capabilities
3126 control16(c
, 9, t
, 1); // assigned tunnel
3127 controladd(c
, 0, t
); // send
3131 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3137 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3141 LOG(3, s
, t
, "Received SCCN\n");
3142 tunnel
[t
].state
= TUNNELOPEN
;
3143 tunnel
[t
].lastrec
= time_now
;
3144 controlnull(t
); // ack
3147 LOG(3, s
, t
, "Received StopCCN\n");
3148 controlnull(t
); // ack
3149 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3152 LOG(3, s
, t
, "Received HELLO\n");
3153 controlnull(t
); // simply ACK
3157 LOG(3, s
, t
, "Received OCRQ\n");
3161 LOG(3, s
, t
, "Received OCRO\n");
3165 LOG(3, s
, t
, "Received OCCN\n");
3168 LOG(3, s
, t
, "Received ICRQ\n");
3169 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3171 controlt
*c
= controlnew(11); // ICRP
3173 LOG(3, s
, t
, "Sending ICRP\n");
3176 sessionfree
= session
[s
].next
;
3177 memset(&session
[s
], 0, sizeof(session
[s
]));
3179 if (s
> config
->cluster_highest_sessionid
)
3180 config
->cluster_highest_sessionid
= s
;
3182 session
[s
].opened
= time_now
;
3183 session
[s
].tunnel
= t
;
3184 session
[s
].far
= asession
;
3185 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3186 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3187 control16(c
, 14, s
, 1); // assigned session
3188 controladd(c
, asession
, t
); // send the reply
3190 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3191 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3193 session
[s
].ppp
.phase
= Establish
;
3194 session
[s
].ppp
.lcp
= Starting
;
3196 STAT(session_created
);
3201 controlt
*c
= controlnew(14); // CDN
3202 LOG(3, s
, t
, "Sending CDN\n");
3205 STAT(session_overflow
);
3206 LOG(1, 0, t
, "No free sessions\n");
3207 control16(c
, 1, 4, 0); // temporary lack of resources
3210 control16(c
, 1, 2, 7); // shutting down, try another
3212 controladd(c
, asession
, t
); // send the message
3216 LOG(3, s
, t
, "Received ICRP\n");
3217 if (session
[s
].forwardtosession
)
3219 controlt
*c
= controlnew(12); // ICCN
3221 session
[s
].opened
= time_now
;
3222 session
[s
].tunnel
= t
;
3223 session
[s
].far
= asession
;
3224 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3226 control32(c
, 19, 1, 1); // Framing Type
3227 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3228 controladd(c
, asession
, t
); // send the message
3229 LOG(3, s
, t
, "Sending ICCN\n");
3233 LOG(3, s
, t
, "Received ICCN\n");
3234 if (amagic
== 0) amagic
= time_now
;
3235 session
[s
].magic
= amagic
; // set magic number
3236 session
[s
].flags
= aflags
; // set flags received
3237 session
[s
].mru
= PPPoE_MRU
; // default
3238 controlnull(t
); // ack
3241 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3242 sess_local
[s
].ppp_mru
= MRU
;
3244 // Set multilink options before sending initial LCP packet
3245 sess_local
[s
].mp_mrru
= 1614;
3246 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] : my_address
);
3249 change_state(s
, lcp
, RequestSent
);
3253 LOG(3, s
, t
, "Received CDN\n");
3254 controlnull(t
); // ack
3255 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3258 LOG(1, s
, t
, "Missing message type\n");
3261 STAT(tunnel_rx_errors
);
3263 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3265 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3268 if (chapresponse
) free(chapresponse
);
3269 cluster_send_tunnel(t
);
3273 LOG(4, s
, t
, " Got a ZLB ack\n");
3280 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3281 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3282 { // HDLC address header, discard
3288 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3289 STAT(tunnel_rx_errors
);
3299 proto
= ntohs(*(uint16_t *) p
);
3304 if (session
[s
].forwardtosession
)
3306 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3307 // Forward to LAC/BAS or Remote LNS session
3308 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3311 else if (config
->auth_tunnel_change_addr_src
)
3313 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3314 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3316 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3317 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3318 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3320 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3324 if (s
&& !session
[s
].opened
) // Is something wrong??
3326 if (!config
->cluster_iam_master
)
3328 // Pass it off to the master to deal with..
3329 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3333 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3334 STAT(tunnel_rx_errors
);
3338 if (proto
== PPPPAP
)
3340 session
[s
].last_packet
= time_now
;
3341 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3342 processpap(s
, t
, p
, l
);
3344 else if (proto
== PPPCHAP
)
3346 session
[s
].last_packet
= time_now
;
3347 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3348 processchap(s
, t
, p
, l
);
3350 else if (proto
== PPPLCP
)
3352 session
[s
].last_packet
= time_now
;
3353 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3354 processlcp(s
, t
, p
, l
);
3356 else if (proto
== PPPIPCP
)
3358 session
[s
].last_packet
= time_now
;
3359 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3360 processipcp(s
, t
, p
, l
);
3362 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3364 session
[s
].last_packet
= time_now
;
3365 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3366 processipv6cp(s
, t
, p
, l
);
3368 else if (proto
== PPPCCP
)
3370 session
[s
].last_packet
= time_now
;
3371 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3372 processccp(s
, t
, p
, l
);
3374 else if (proto
== PPPIP
)
3378 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3379 return; // closing session, PPP not processed
3382 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3383 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3385 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3389 processipin(s
, t
, p
, l
);
3391 else if (proto
== PPPMP
)
3395 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3396 return; // closing session, PPP not processed
3399 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3400 if (!config
->cluster_iam_master
)
3402 // The fragments reconstruction is managed by the Master.
3403 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3407 processmpin(s
, t
, p
, l
);
3409 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3413 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3414 return; // closing session, PPP not processed
3417 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3418 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3420 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3424 processipv6in(s
, t
, p
, l
);
3426 else if (session
[s
].ppp
.lcp
== Opened
)
3428 session
[s
].last_packet
= time_now
;
3429 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3430 protoreject(s
, t
, p
, l
, proto
);
3434 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3435 proto
, ppp_state(session
[s
].ppp
.lcp
));
3440 // read and process packet on tun
3441 // (i.e. this routine writes to buf[-8]).
3442 static void processtun(uint8_t * buf
, int len
)
3444 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3445 STAT(tun_rx_packets
);
3446 INC_STAT(tun_rx_bytes
, len
);
3454 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3455 STAT(tun_rx_errors
);
3459 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3460 processipout(buf
, len
);
3461 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3462 && config
->ipv6_prefix
.s6_addr
[0])
3463 processipv6out(buf
, len
);
3468 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3469 // that we look at the whole of the tunnel, radius and session tables
3471 static void regular_cleanups(double period
)
3473 // Next tunnel, radius and session to check for actions on.
3474 static tunnelidt t
= 0;
3476 static sessionidt s
= 0;
3489 // divide up tables into slices based on the last run
3490 t_slice
= config
->cluster_highest_tunnelid
* period
;
3491 r_slice
= (MAXRADIUS
- 1) * period
;
3492 s_slice
= config
->cluster_highest_sessionid
* period
;
3496 else if (t_slice
> config
->cluster_highest_tunnelid
)
3497 t_slice
= config
->cluster_highest_tunnelid
;
3501 else if (r_slice
> (MAXRADIUS
- 1))
3502 r_slice
= MAXRADIUS
- 1;
3506 else if (s_slice
> config
->cluster_highest_sessionid
)
3507 s_slice
= config
->cluster_highest_sessionid
;
3509 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3511 for (i
= 0; i
< t_slice
; i
++)
3514 if (t
> config
->cluster_highest_tunnelid
)
3517 if (t
== TUNNEL_ID_PPPOE
)
3520 // check for expired tunnels
3521 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3523 STAT(tunnel_timeout
);
3524 tunnelkill(t
, "Expired");
3528 // check for message resend
3529 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3531 // resend pending messages as timeout on reply
3532 if (tunnel
[t
].retry
<= TIME
)
3534 controlt
*c
= tunnel
[t
].controls
;
3535 uint16_t w
= tunnel
[t
].window
;
3536 tunnel
[t
].try++; // another try
3537 if (tunnel
[t
].try > 5)
3538 tunnelkill(t
, "Timeout on control message"); // game over
3542 tunnelsend(c
->buf
, c
->length
, t
);
3550 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3552 if (!config
->disable_sending_hello
)
3554 controlt
*c
= controlnew(6); // sending HELLO
3555 controladd(c
, 0, t
); // send the message
3556 LOG(3, 0, t
, "Sending HELLO message\n");
3561 // Check for tunnel changes requested from the CLI
3562 if ((a
= cli_tunnel_actions
[t
].action
))
3564 cli_tunnel_actions
[t
].action
= 0;
3565 if (a
& CLI_TUN_KILL
)
3567 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3568 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3574 for (i
= 0; i
< r_slice
; i
++)
3580 if (!radius
[r
].state
)
3583 if (radius
[r
].retry
<= TIME
)
3590 for (i
= 0; i
< s_slice
; i
++)
3593 if (s
> config
->cluster_highest_sessionid
)
3596 if (!session
[s
].opened
) // Session isn't in use
3599 // check for expired sessions
3602 if (session
[s
].die
<= TIME
)
3604 sessionkill(s
, "Expired");
3611 if (sess_local
[s
].lcp
.restart
<= time_now
)
3613 int next_state
= session
[s
].ppp
.lcp
;
3614 switch (session
[s
].ppp
.lcp
)
3618 next_state
= RequestSent
;
3621 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3623 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3624 sendlcp(s
, session
[s
].tunnel
);
3625 change_state(s
, lcp
, next_state
);
3629 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3630 STAT(session_timeout
);
3640 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3642 int next_state
= session
[s
].ppp
.ipcp
;
3643 switch (session
[s
].ppp
.ipcp
)
3647 next_state
= RequestSent
;
3650 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3652 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3653 sendipcp(s
, session
[s
].tunnel
);
3654 change_state(s
, ipcp
, next_state
);
3658 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3659 STAT(session_timeout
);
3669 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3671 int next_state
= session
[s
].ppp
.ipv6cp
;
3672 switch (session
[s
].ppp
.ipv6cp
)
3676 next_state
= RequestSent
;
3679 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3681 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3682 sendipv6cp(s
, session
[s
].tunnel
);
3683 change_state(s
, ipv6cp
, next_state
);
3687 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3688 change_state(s
, ipv6cp
, Stopped
);
3695 if (sess_local
[s
].ccp
.restart
<= time_now
)
3697 int next_state
= session
[s
].ppp
.ccp
;
3698 switch (session
[s
].ppp
.ccp
)
3702 next_state
= RequestSent
;
3705 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3707 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3708 sendccp(s
, session
[s
].tunnel
);
3709 change_state(s
, ccp
, next_state
);
3713 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3714 change_state(s
, ccp
, Stopped
);
3721 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3722 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3724 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3725 STAT(session_timeout
);
3730 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3731 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= config
->echo_timeout
) &&
3732 (time_now
- sess_local
[s
].last_echo
>= config
->echo_timeout
))
3734 uint8_t b
[MAXETHER
];
3736 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3740 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3741 *(uint16_t *)(q
+ 2) = htons(8); // Length
3742 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3744 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3745 (int)(time_now
- session
[s
].last_packet
));
3747 tunnelsend(b
, (q
- b
) + 8, session
[s
].tunnel
); // send it
3748 sess_local
[s
].last_echo
= time_now
;
3752 // Drop sessions who have reached session_timeout seconds
3753 if (session
[s
].session_timeout
)
3755 bundleidt bid
= session
[s
].bundle
;
3758 if (time_now
- bundle
[bid
].last_check
>= 1)
3760 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3761 bundle
[bid
].last_check
= time_now
;
3762 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3765 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3767 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3774 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3776 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3782 // Drop sessions who have reached idle_timeout seconds
3783 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3785 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3786 STAT(session_timeout
);
3791 // Check for actions requested from the CLI
3792 if ((a
= cli_session_actions
[s
].action
))
3796 cli_session_actions
[s
].action
= 0;
3797 if (a
& CLI_SESS_KILL
)
3799 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3800 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3801 a
= 0; // dead, no need to check for other actions
3805 if (a
& CLI_SESS_NOSNOOP
)
3807 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3808 session
[s
].snoop_ip
= 0;
3809 session
[s
].snoop_port
= 0;
3813 else if (a
& CLI_SESS_SNOOP
)
3815 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3816 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3817 cli_session_actions
[s
].snoop_port
);
3819 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3820 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3825 if (a
& CLI_SESS_NOTHROTTLE
)
3827 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3828 throttle_session(s
, 0, 0);
3832 else if (a
& CLI_SESS_THROTTLE
)
3834 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3835 cli_session_actions
[s
].throttle_in
,
3836 cli_session_actions
[s
].throttle_out
);
3838 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3843 if (a
& CLI_SESS_NOFILTER
)
3845 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3846 filter_session(s
, 0, 0);
3850 else if (a
& CLI_SESS_FILTER
)
3852 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3853 cli_session_actions
[s
].filter_in
,
3854 cli_session_actions
[s
].filter_out
);
3856 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3862 cluster_send_session(s
);
3865 // RADIUS interim accounting
3866 if (config
->radius_accounting
&& config
->radius_interim
> 0
3867 && session
[s
].ip
&& !session
[s
].walled_garden
3868 && !sess_local
[s
].radius
// RADIUS already in progress
3869 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3870 && session
[s
].flags
& SESSION_STARTED
)
3872 int rad
= radiusnew(s
);
3875 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3876 STAT(radius_overflow
);
3880 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3881 session
[s
].user
, session
[s
].unique_id
);
3883 radiussend(rad
, RADIUSINTERIM
);
3884 sess_local
[s
].last_interim
= time_now
;
3889 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3890 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3894 // Are we in the middle of a tunnel update, or radius
3897 static int still_busy(void)
3900 static clockt last_talked
= 0;
3901 static clockt start_busy_wait
= 0;
3904 static time_t stopped_bgp
= 0;
3909 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3911 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3912 if (bgp_peers
[i
].state
== Established
)
3913 bgp_stop(&bgp_peers
[i
]);
3915 stopped_bgp
= time_now
;
3917 if (!config
->cluster_iam_master
)
3919 // we don't want to become master
3920 cluster_send_ping(0);
3926 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3931 if (!config
->cluster_iam_master
)
3934 if (main_quit
== QUIT_SHUTDOWN
)
3936 static int dropped
= 0;
3941 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3942 for (i
= 1; i
< MAXTUNNEL
; i
++)
3943 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3944 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3950 if (start_busy_wait
== 0)
3951 start_busy_wait
= TIME
;
3953 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3955 if (!tunnel
[i
].controlc
)
3958 if (last_talked
!= TIME
)
3960 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3966 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3967 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3969 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3973 for (i
= 1; i
< MAXRADIUS
; i
++)
3975 if (radius
[i
].state
== RADIUSNULL
)
3977 if (radius
[i
].state
== RADIUSWAIT
)
3980 if (last_talked
!= TIME
)
3982 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3992 # include <sys/epoll.h>
3994 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3995 # include "fake_epoll.h"
3998 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
3999 #define BASE_FDS (9 + MAX_UDPFD)
4001 // additional polled fds
4003 # define EXTRA_FDS BGP_NUM_PEERS
4005 # define EXTRA_FDS 0
4008 // main loop - gets packets on tun or udp and processes them
4009 static void mainloop(void)
4013 uint8_t *p
= buf
+ 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4014 // and the forwarded pppoe session
4015 int size_bufp
= sizeof(buf
) - 32;
4016 clockt next_cluster_ping
= 0; // send initial ping immediately
4017 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
4018 int maxevent
= sizeof(events
)/sizeof(*events
);
4020 if ((epollfd
= epoll_create(maxevent
)) < 0)
4022 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
4026 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",
4027 clifd
, cluster_sockfd
, tunfd
, udpfd
[0], controlfd
, daefd
, nlfd
, udplacfd
, pppoediscfd
, pppoesessfd
);
4029 /* setup our fds to poll for input */
4031 static struct event_data d
[BASE_FDS
];
4032 struct epoll_event e
;
4039 d
[i
].type
= FD_TYPE_CLI
;
4040 e
.data
.ptr
= &d
[i
++];
4041 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
4044 d
[i
].type
= FD_TYPE_CLUSTER
;
4045 e
.data
.ptr
= &d
[i
++];
4046 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
4048 d
[i
].type
= FD_TYPE_TUN
;
4049 e
.data
.ptr
= &d
[i
++];
4050 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
4052 d
[i
].type
= FD_TYPE_CONTROL
;
4053 e
.data
.ptr
= &d
[i
++];
4054 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
4056 d
[i
].type
= FD_TYPE_DAE
;
4057 e
.data
.ptr
= &d
[i
++];
4058 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
4060 d
[i
].type
= FD_TYPE_NETLINK
;
4061 e
.data
.ptr
= &d
[i
++];
4062 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
4064 d
[i
].type
= FD_TYPE_PPPOEDISC
;
4065 e
.data
.ptr
= &d
[i
++];
4066 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoediscfd
, &e
);
4068 d
[i
].type
= FD_TYPE_PPPOESESS
;
4069 e
.data
.ptr
= &d
[i
++];
4070 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoesessfd
, &e
);
4072 for (j
= 0; j
< config
->nbudpfd
; j
++)
4074 d
[i
].type
= FD_TYPE_UDP
;
4076 e
.data
.ptr
= &d
[i
++];
4077 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
[j
], &e
);
4082 signal(SIGPIPE
, SIG_IGN
);
4083 bgp_setup(config
->as_number
);
4084 if (config
->bind_address
)
4085 bgp_add_route(config
->bind_address
, 0xffffffff);
4087 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4089 if (config
->neighbour
[i
].name
[0])
4090 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4091 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4092 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4093 0); /* 0 = routing disabled */
4097 while (!main_quit
|| still_busy())
4107 config
->reload_config
++;
4110 if (config
->reload_config
)
4112 config
->reload_config
= 0;
4120 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4121 STAT(select_called
);
4126 if (errno
== EINTR
||
4127 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4130 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4136 struct sockaddr_in addr
;
4137 struct in_addr local
;
4140 int udp_ready
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4141 int pppoesess_ready
= 0;
4142 int pppoesess_pkts
= 0;
4144 int cluster_ready
= 0;
4145 int udp_pkts
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4147 int cluster_pkts
= 0;
4149 uint32_t bgp_events
[BGP_NUM_PEERS
];
4150 memset(bgp_events
, 0, sizeof(bgp_events
));
4153 for (c
= n
, i
= 0; i
< c
; i
++)
4155 struct event_data
*d
= events
[i
].data
.ptr
;
4159 case FD_TYPE_CLI
: // CLI connections
4163 alen
= sizeof(addr
);
4164 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4170 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4176 // these are handled below, with multiple interleaved reads
4177 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4178 case FD_TYPE_TUN
: tun_ready
++; break;
4179 case FD_TYPE_UDP
: udp_ready
[d
->index
]++; break;
4180 case FD_TYPE_PPPOESESS
: pppoesess_ready
++; break;
4182 case FD_TYPE_PPPOEDISC
: // pppoe discovery
4183 s
= read(pppoediscfd
, p
, size_bufp
);
4184 if (s
> 0) process_pppoe_disc(p
, s
);
4188 case FD_TYPE_CONTROL
: // nsctl commands
4189 alen
= sizeof(addr
);
4190 s
= recvfromto(controlfd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4191 if (s
> 0) processcontrol(p
, s
, &addr
, alen
, &local
);
4195 case FD_TYPE_DAE
: // DAE requests
4196 alen
= sizeof(addr
);
4197 s
= recvfromto(daefd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4198 if (s
> 0) processdae(p
, s
, &addr
, alen
, &local
);
4202 case FD_TYPE_RADIUS
: // RADIUS response
4203 alen
= sizeof(addr
);
4204 s
= recvfrom(radfds
[d
->index
], p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4205 if (s
>= 0 && config
->cluster_iam_master
)
4207 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4208 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4209 processrad(p
, s
, d
->index
);
4211 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4212 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4220 bgp_events
[d
->index
] = events
[i
].events
;
4225 case FD_TYPE_NETLINK
:
4227 struct nlmsghdr
*nh
= (struct nlmsghdr
*)p
;
4228 s
= netlink_recv(p
, size_bufp
);
4229 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4231 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4234 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4236 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4240 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4245 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
);
4251 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4256 bgp_process(bgp_events
);
4259 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4261 for (j
= 0; j
< config
->nbudpfd
; j
++)
4263 // L2TP and L2TP REMOTE LNS
4266 alen
= sizeof(addr
);
4267 if ((s
= recvfrom(udpfd
[j
], p
, size_bufp
, 0, (void *) &addr
, &alen
)) > 0)
4269 processudp(p
, s
, &addr
, j
);
4283 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4296 if (pppoesess_ready
)
4298 if ((s
= read(pppoesessfd
, p
, size_bufp
)) > 0)
4300 process_pppoe_sess(p
, s
);
4305 pppoesess_ready
= 0;
4313 alen
= sizeof(addr
);
4314 if ((s
= recvfrom(cluster_sockfd
, p
, size_bufp
, MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4316 processcluster(p
, s
, addr
.sin_addr
.s_addr
);
4327 if (udp_pkts
[0] > 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4328 STAT(multi_read_used
);
4330 if (c
>= config
->multi_read_count
)
4332 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4333 config
->multi_read_count
, udp_pkts
[0], tun_pkts
, cluster_pkts
, pppoesess_pkts
);
4334 STAT(multi_read_exceeded
);
4340 /* no event received, but timers could still have expired */
4341 bgp_process_peers_timers();
4346 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4348 // Log current traffic stats
4349 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4350 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4351 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4352 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4353 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4355 udp_tx
= udp_rx
= 0;
4356 udp_rx_pkt
= eth_rx_pkt
= 0;
4357 eth_tx
= eth_rx
= 0;
4360 if (config
->dump_speed
)
4361 printf("%s\n", config
->bandwidth
);
4363 // Update the internal time counter
4364 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4368 struct param_timer p
= { time_now
};
4369 run_plugins(PLUGIN_TIMER
, &p
);
4373 // Runs on every machine (master and slaves).
4374 if (next_cluster_ping
<= TIME
)
4376 // Check to see which of the cluster is still alive..
4378 cluster_send_ping(basetime
); // Only does anything if we're a slave
4379 cluster_check_master(); // ditto.
4381 cluster_heartbeat(); // Only does anything if we're a master.
4382 cluster_check_slaves(); // ditto.
4384 master_update_counts(); // If we're a slave, send our byte counters to our master.
4386 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4387 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4389 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4392 if (!config
->cluster_iam_master
)
4395 // Run token bucket filtering queue..
4396 // Only run it every 1/10th of a second.
4398 static clockt last_run
= 0;
4399 if (last_run
!= TIME
)
4406 // Handle timeouts, retries etc.
4408 static double last_clean
= 0;
4412 TIME
= now(&this_clean
);
4413 diff
= this_clean
- last_clean
;
4415 // Run during idle time (after we've handled
4416 // all incoming packets) or every 1/10th sec
4417 if (!more
|| diff
> 0.1)
4419 regular_cleanups(diff
);
4420 last_clean
= this_clean
;
4424 if (*config
->accounting_dir
)
4426 static clockt next_acct
= 0;
4427 static clockt next_shut_acct
= 0;
4429 if (next_acct
<= TIME
)
4431 // Dump accounting data
4432 next_acct
= TIME
+ ACCT_TIME
;
4433 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4436 else if (next_shut_acct
<= TIME
)
4438 // Dump accounting data for shutdown sessions
4439 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4446 // Are we the master and shutting down??
4447 if (config
->cluster_iam_master
)
4448 cluster_heartbeat(); // Flush any queued changes..
4450 // Ok. Notify everyone we're shutting down. If we're
4451 // the master, this will force an election.
4452 cluster_send_ping(0);
4455 // Important!!! We MUST not process any packets past this point!
4456 LOG(1, 0, 0, "Shutdown complete\n");
4459 static void stripdomain(char *host
)
4463 if ((p
= strchr(host
, '.')))
4469 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4475 while (fgets(buf
, sizeof(buf
), resolv
))
4477 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4480 if (!isspace(buf
[6]))
4484 while (isspace(*b
)) b
++;
4489 while (*b
&& !isspace(*b
)) b
++;
4491 if (buf
[0] == 'd') // domain is canonical
4497 // first search line
4500 // hold, may be subsequent domain line
4501 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4512 int hl
= strlen(host
);
4513 int dl
= strlen(domain
);
4514 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4515 host
[hl
-dl
- 1] = 0;
4519 *p
= 0; // everything after first dot
4524 // Init data structures
4525 static void initdata(int optdebug
, char *optconfig
)
4529 if (!(config
= shared_malloc(sizeof(configt
))))
4531 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4535 memset(config
, 0, sizeof(configt
));
4536 time(&config
->start_time
);
4537 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4538 config
->debug
= optdebug
;
4539 config
->num_tbfs
= MAXTBFS
;
4540 config
->rl_rate
= 28; // 28kbps
4541 config
->cluster_mcast_ttl
= 1;
4542 config
->cluster_master_min_adv
= 1;
4543 config
->ppp_restart_time
= 3;
4544 config
->ppp_max_configure
= 10;
4545 config
->ppp_max_failure
= 5;
4546 config
->kill_timedout_sessions
= 1;
4547 strcpy(config
->random_device
, RANDOMDEVICE
);
4548 // Set default value echo_timeout and idle_echo_timeout
4549 config
->echo_timeout
= ECHO_TIMEOUT
;
4550 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4552 log_stream
= stderr
;
4555 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4557 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4560 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4563 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4565 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4568 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4570 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4573 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4575 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4578 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4580 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4583 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4585 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4589 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4591 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4595 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4597 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4601 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4603 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4607 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4609 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4612 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4614 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4616 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4619 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4621 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4623 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4626 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4628 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4629 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4630 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4631 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4632 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4634 // Put all the sessions on the free list marked as undefined.
4635 for (i
= 1; i
< MAXSESSION
; i
++)
4637 session
[i
].next
= i
+ 1;
4638 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4640 session
[MAXSESSION
- 1].next
= 0;
4643 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4644 for (i
= 1; i
< MAXTUNNEL
; i
++)
4645 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4647 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4648 bundle
[i
].state
= BUNDLEUNDEF
;
4653 // Grab my hostname unless it's been specified
4654 gethostname(hostname
, sizeof(hostname
));
4655 stripdomain(hostname
);
4658 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4661 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4663 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4668 lac_initremotelnsdata();
4673 static int assign_ip_address(sessionidt s
)
4677 time_t best_time
= time_now
;
4678 char *u
= session
[s
].user
;
4682 CSTAT(assign_ip_address
);
4684 for (i
= 1; i
< ip_pool_size
; i
++)
4686 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4689 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4696 if (ip_address_pool
[i
].last
< best_time
)
4699 if (!(best_time
= ip_address_pool
[i
].last
))
4700 break; // never used, grab this one
4706 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4710 session
[s
].ip
= ip_address_pool
[best
].address
;
4711 session
[s
].ip_pool_index
= best
;
4712 ip_address_pool
[best
].assigned
= 1;
4713 ip_address_pool
[best
].last
= time_now
;
4714 ip_address_pool
[best
].session
= s
;
4715 if (session
[s
].walled_garden
)
4716 /* Don't track addresses of users in walled garden (note: this
4717 means that their address isn't "sticky" even if they get
4719 ip_address_pool
[best
].user
[0] = 0;
4721 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4724 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4725 reuse
? "Reusing" : "Allocating", best
);
4730 static void free_ip_address(sessionidt s
)
4732 int i
= session
[s
].ip_pool_index
;
4735 CSTAT(free_ip_address
);
4738 return; // what the?
4740 if (i
< 0) // Is this actually part of the ip pool?
4744 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4746 ip_address_pool
[i
].assigned
= 0;
4747 ip_address_pool
[i
].session
= 0;
4748 ip_address_pool
[i
].last
= time_now
;
4752 // Fsck the address pool against the session table.
4753 // Normally only called when we become a master.
4755 // This isn't perfect: We aren't keep tracking of which
4756 // users used to have an IP address.
4758 void rebuild_address_pool(void)
4763 // Zero the IP pool allocation, and build
4764 // a map from IP address to pool index.
4765 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4767 ip_address_pool
[i
].assigned
= 0;
4768 ip_address_pool
[i
].session
= 0;
4769 if (!ip_address_pool
[i
].address
)
4772 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4775 for (i
= 0; i
< MAXSESSION
; ++i
)
4778 if (!(session
[i
].opened
&& session
[i
].ip
))
4781 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4783 if (session
[i
].ip_pool_index
< 0)
4785 // Not allocated out of the pool.
4786 if (ipid
< 1) // Not found in the pool either? good.
4789 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4790 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4792 // Fall through and process it as part of the pool.
4796 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4798 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4800 session
[i
].ip_pool_index
= ipid
;
4804 ip_address_pool
[ipid
].assigned
= 1;
4805 ip_address_pool
[ipid
].session
= i
;
4806 ip_address_pool
[ipid
].last
= time_now
;
4807 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4808 session
[i
].ip_pool_index
= ipid
;
4809 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4814 // Fix the address pool to match a changed session.
4815 // (usually when the master sends us an update).
4816 static void fix_address_pool(int sid
)
4820 ipid
= session
[sid
].ip_pool_index
;
4822 if (ipid
> ip_pool_size
)
4823 return; // Ignore it. rebuild_address_pool will fix it up.
4825 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4826 return; // Just ignore it. rebuild_address_pool will take care of it.
4828 ip_address_pool
[ipid
].assigned
= 1;
4829 ip_address_pool
[ipid
].session
= sid
;
4830 ip_address_pool
[ipid
].last
= time_now
;
4831 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4835 // Add a block of addresses to the IP pool to hand out.
4837 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4841 prefixlen
= 32; // Host route only.
4843 addr
&= 0xffffffff << (32 - prefixlen
);
4845 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4848 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4850 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4851 continue; // Skip 0 and broadcast addresses.
4853 ip_address_pool
[ip_pool_size
].address
= i
;
4854 ip_address_pool
[ip_pool_size
].assigned
= 0;
4856 if (ip_pool_size
>= MAXIPPOOL
)
4858 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4864 // Initialize the IP address pool
4865 static void initippool()
4870 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4872 if (!(f
= fopen(IPPOOLFILE
, "r")))
4874 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4878 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4881 buf
[4095] = 0; // Force it to be zero terminated/
4883 if (*buf
== '#' || *buf
== '\n')
4884 continue; // Skip comments / blank lines
4885 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4886 if ((p
= (char *)strchr(buf
, ':')))
4890 src
= inet_addr(buf
);
4891 if (src
== INADDR_NONE
)
4893 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4896 // This entry is for a specific IP only
4897 if (src
!= config
->bind_address
)
4902 if ((p
= (char *)strchr(pool
, '/')))
4906 in_addr_t start
= 0;
4908 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4910 if (!*p
|| !(numbits
= atoi(p
)))
4912 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4915 start
= ntohl(inet_addr(pool
));
4917 // Add a static route for this pool
4918 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4919 fmtaddr(htonl(start
), 0), numbits
);
4921 routeset(0, start
, numbits
, 0, 1);
4923 add_to_ip_pool(start
, numbits
);
4927 // It's a single ip address
4928 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4932 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4935 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4937 struct sockaddr_in snoop_addr
= {0};
4938 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4941 snoop_addr
.sin_family
= AF_INET
;
4942 snoop_addr
.sin_addr
.s_addr
= destination
;
4943 snoop_addr
.sin_port
= ntohs(port
);
4945 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4946 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4947 htons(snoop_addr
.sin_port
));
4949 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4950 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4952 STAT(packets_snooped
);
4955 static int dump_session(FILE **f
, sessiont
*s
)
4957 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4962 char filename
[1024];
4964 time_t now
= time(NULL
);
4966 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4967 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4969 if (!(*f
= fopen(filename
, "w")))
4971 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4975 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4976 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4981 "# format: username ip qos uptxoctets downrxoctets\n",
4983 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
4988 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4989 fprintf(*f
, "%s %s %d %u %u\n",
4990 s
->user
, // username
4991 fmtaddr(htonl(s
->ip
), 0), // ip
4992 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4993 (uint32_t) s
->cin_delta
, // uptxoctets
4994 (uint32_t) s
->cout_delta
); // downrxoctets
4996 s
->cin_delta
= s
->cout_delta
= 0;
5001 static void dump_acct_info(int all
)
5007 CSTAT(dump_acct_info
);
5011 for (i
= 0; i
< shut_acct_n
; i
++)
5012 dump_session(&f
, &shut_acct
[i
]);
5018 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5019 dump_session(&f
, &session
[i
]);
5026 int main(int argc
, char *argv
[])
5030 char *optconfig
= CONFIGFILE
;
5032 time(&basetime
); // start clock
5035 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
5040 if (fork()) exit(0);
5042 freopen("/dev/null", "r", stdin
);
5043 freopen("/dev/null", "w", stdout
);
5044 freopen("/dev/null", "w", stderr
);
5053 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
5056 printf("Args are:\n"
5057 "\t-d\t\tDetach from terminal\n"
5058 "\t-c <file>\tConfig file\n"
5059 "\t-h <hostname>\tForce hostname\n"
5067 // Start the timer routine off
5069 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5072 initdata(optdebug
, optconfig
);
5076 /* set hostname /after/ having read the config file */
5077 if (*config
->hostname
)
5078 strcpy(hostname
, config
->hostname
);
5079 cli_init_complete(hostname
);
5081 init_tbf(config
->num_tbfs
);
5083 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5084 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5085 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5088 rlim
.rlim_cur
= RLIM_INFINITY
;
5089 rlim
.rlim_max
= RLIM_INFINITY
;
5090 // Remove the maximum core size
5091 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5092 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5094 // Make core dumps go to /tmp
5098 if (config
->scheduler_fifo
)
5101 struct sched_param params
= {0};
5102 params
.sched_priority
= 1;
5104 if (get_nprocs() < 2)
5106 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5107 config
->scheduler_fifo
= 0;
5111 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5113 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5117 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5118 config
->scheduler_fifo
= 0;
5125 /* Set up the cluster communications port. */
5126 if (cluster_init() < 0)
5130 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5132 if (*config
->pppoe_if_to_bind
)
5135 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config
->pppoe_if_to_bind
);
5138 if (!config
->nbmultiaddress
)
5140 config
->bind_n_address
[0] = config
->bind_address
;
5141 config
->nbmultiaddress
++;
5143 config
->nbudpfd
= config
->nbmultiaddress
;
5144 for (i
= 0; i
< config
->nbudpfd
; i
++)
5145 initudp(&udpfd
[i
], config
->bind_n_address
[i
]);
5147 config
->indexlacudpfd
= config
->nbudpfd
;
5148 udpfd
[config
->indexlacudpfd
] = udplacfd
;
5155 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
5162 unsigned seed
= time_now
^ getpid();
5163 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5167 signal(SIGHUP
, sighup_handler
);
5168 signal(SIGCHLD
, sigchild_handler
);
5169 signal(SIGTERM
, shutdown_handler
);
5170 signal(SIGINT
, shutdown_handler
);
5171 signal(SIGQUIT
, shutdown_handler
);
5173 // Prevent us from getting paged out
5174 if (config
->lock_pages
)
5176 if (!mlockall(MCL_CURRENT
))
5177 LOG(1, 0, 0, "Locking pages into memory\n");
5179 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
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);
5685 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5686 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5688 // Run the plugin's against this new session.
5690 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5691 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5694 // Allocate TBFs if throttled
5695 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5696 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5698 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5700 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5701 fmtaddr(htonl(session
[s
].ip
), 0),
5702 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5704 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5706 return 1; // RADIUS OK and IP allocated, done...
5710 // This session just got dropped on us by the master or something.
5711 // Make sure our tables up up to date...
5713 int load_session(sessionidt s
, sessiont
*new)
5719 if (new->ip_pool_index
>= MAXIPPOOL
||
5720 new->tunnel
>= MAXTUNNEL
)
5722 LOG(0, s
, 0, "Strange session update received!\n");
5723 // FIXME! What to do here?
5728 // Ok. All sanity checks passed. Now we're committed to
5729 // loading the new session.
5732 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5734 // See if routes/ip cache need updating
5735 if (new->ip
!= session
[s
].ip
)
5738 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5739 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5740 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5748 // remove old routes...
5749 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5751 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5752 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5755 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5761 if (session
[s
].ip_pool_index
== -1) // static IP
5763 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5765 else // It's part of the IP pool, remove it manually.
5766 uncache_ipmap(session
[s
].ip
);
5771 // add new routes...
5772 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5774 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5775 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5778 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5784 // If there's a new one, add it.
5785 if (new->ip_pool_index
== -1)
5787 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5790 cache_ipmap(new->ip
, s
);
5795 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5796 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5799 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5801 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5805 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5807 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5808 new->filter_out
= 0;
5811 if (new->filter_in
!= session
[s
].filter_in
)
5813 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5814 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5817 if (new->filter_out
!= session
[s
].filter_out
)
5819 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5820 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5823 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5824 // for walking the sessions to forward byte counts to the master.
5825 config
->cluster_highest_sessionid
= s
;
5827 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5829 // Do fixups into address pool.
5830 if (new->ip_pool_index
!= -1)
5831 fix_address_pool(s
);
5836 static void initplugins()
5840 loaded_plugins
= ll_init();
5841 // Initialize the plugins to nothing
5842 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5843 plugins
[i
] = ll_init();
5846 static void *open_plugin(char *plugin_name
, int load
)
5848 char path
[256] = "";
5850 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5851 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5852 return dlopen(path
, RTLD_NOW
);
5855 // plugin callback to get a config value
5856 static void *getconfig(char *key
, enum config_typet type
)
5860 for (i
= 0; config_values
[i
].key
; i
++)
5862 if (!strcmp(config_values
[i
].key
, key
))
5864 if (config_values
[i
].type
== type
)
5865 return ((void *) config
) + config_values
[i
].offset
;
5867 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5868 key
, type
, config_values
[i
].type
);
5874 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5878 static int add_plugin(char *plugin_name
)
5880 static struct pluginfuncs funcs
= {
5885 sessiontbysessionidt
,
5886 sessionidtbysessiont
,
5893 cluster_send_session
,
5896 void *p
= open_plugin(plugin_name
, 1);
5897 int (*initfunc
)(struct pluginfuncs
*);
5902 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5906 if (ll_contains(loaded_plugins
, p
))
5909 return 0; // already loaded
5913 int *v
= dlsym(p
, "plugin_api_version");
5914 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5916 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5922 if ((initfunc
= dlsym(p
, "plugin_init")))
5924 if (!initfunc(&funcs
))
5926 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5932 ll_push(loaded_plugins
, p
);
5934 for (i
= 0; i
< max_plugin_functions
; i
++)
5937 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5939 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5940 ll_push(plugins
[i
], x
);
5944 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5948 static void run_plugin_done(void *plugin
)
5950 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5956 static int remove_plugin(char *plugin_name
)
5958 void *p
= open_plugin(plugin_name
, 0);
5964 if (ll_contains(loaded_plugins
, p
))
5967 for (i
= 0; i
< max_plugin_functions
; i
++)
5970 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5971 ll_delete(plugins
[i
], x
);
5974 ll_delete(loaded_plugins
, p
);
5980 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5984 int run_plugins(int plugin_type
, void *data
)
5986 int (*func
)(void *data
);
5988 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5989 return PLUGIN_RET_ERROR
;
5991 ll_reset(plugins
[plugin_type
]);
5992 while ((func
= ll_next(plugins
[plugin_type
])))
5996 if (r
!= PLUGIN_RET_OK
)
5997 return r
; // stop here
6000 return PLUGIN_RET_OK
;
6003 static void plugins_done()
6007 ll_reset(loaded_plugins
);
6008 while ((p
= ll_next(loaded_plugins
)))
6012 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
6014 struct nsctl request
;
6015 struct nsctl response
;
6016 int type
= unpack_control(&request
, buf
, len
);
6020 if (log_stream
&& config
->debug
>= 4)
6024 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6025 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
6029 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6030 dump_control(&request
, log_stream
);
6036 case NSCTL_REQ_LOAD
:
6037 if (request
.argc
!= 1)
6039 response
.type
= NSCTL_RES_ERR
;
6041 response
.argv
[0] = "name of plugin required";
6043 else if ((r
= add_plugin(request
.argv
[0])) < 1)
6045 response
.type
= NSCTL_RES_ERR
;
6047 response
.argv
[0] = !r
6048 ? "plugin already loaded"
6049 : "error loading plugin";
6053 response
.type
= NSCTL_RES_OK
;
6059 case NSCTL_REQ_UNLOAD
:
6060 if (request
.argc
!= 1)
6062 response
.type
= NSCTL_RES_ERR
;
6064 response
.argv
[0] = "name of plugin required";
6066 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
6068 response
.type
= NSCTL_RES_ERR
;
6070 response
.argv
[0] = !r
6071 ? "plugin not loaded"
6072 : "plugin not found";
6076 response
.type
= NSCTL_RES_OK
;
6082 case NSCTL_REQ_HELP
:
6083 response
.type
= NSCTL_RES_OK
;
6086 ll_reset(loaded_plugins
);
6087 while ((p
= ll_next(loaded_plugins
)))
6089 char **help
= dlsym(p
, "plugin_control_help");
6090 while (response
.argc
< 0xff && help
&& *help
)
6091 response
.argv
[response
.argc
++] = *help
++;
6096 case NSCTL_REQ_CONTROL
:
6098 struct param_control param
= {
6099 config
->cluster_iam_master
,
6106 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
6108 if (r
== PLUGIN_RET_ERROR
)
6110 response
.type
= NSCTL_RES_ERR
;
6112 response
.argv
[0] = param
.additional
6114 : "error returned by plugin";
6116 else if (r
== PLUGIN_RET_NOTMASTER
)
6118 static char msg
[] = "must be run on master: 000.000.000.000";
6120 response
.type
= NSCTL_RES_ERR
;
6122 if (config
->cluster_master_address
)
6124 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
6125 response
.argv
[0] = msg
;
6129 response
.argv
[0] = "must be run on master: none elected";
6132 else if (!(param
.response
& NSCTL_RESPONSE
))
6134 response
.type
= NSCTL_RES_ERR
;
6136 response
.argv
[0] = param
.response
6137 ? "unrecognised response value from plugin"
6138 : "unhandled action";
6142 response
.type
= param
.response
;
6144 if (param
.additional
)
6147 response
.argv
[0] = param
.additional
;
6155 response
.type
= NSCTL_RES_ERR
;
6157 response
.argv
[0] = "error unpacking control packet";
6160 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6163 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6167 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6170 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6171 if (log_stream
&& config
->debug
>= 4)
6173 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6174 dump_control(&response
, log_stream
);
6178 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6179 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6184 static tunnelidt
new_tunnel()
6187 for (i
= 1; i
< MAXTUNNEL
; i
++)
6189 if ((tunnel
[i
].state
== TUNNELFREE
) && (i
!= TUNNEL_ID_PPPOE
))
6191 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6192 if (i
> config
->cluster_highest_tunnelid
)
6193 config
->cluster_highest_tunnelid
= i
;
6197 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6202 // We're becoming the master. Do any required setup..
6204 // This is principally telling all the plugins that we're
6205 // now a master, and telling them about all the sessions
6206 // that are active too..
6208 void become_master(void)
6211 static struct event_data d
[RADIUS_FDS
];
6212 struct epoll_event e
;
6214 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6216 // running a bunch of iptables commands is slow and can cause
6217 // the master to drop tunnels on takeover--kludge around the
6218 // problem by forking for the moment (note: race)
6219 if (!fork_and_close())
6221 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6223 if (!session
[s
].opened
) // Not an in-use session.
6226 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6233 for (i
= 0; i
< RADIUS_FDS
; i
++)
6235 d
[i
].type
= FD_TYPE_RADIUS
;
6239 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6243 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6249 if (CLI_HELP_REQUESTED
)
6250 return CLI_HELP_NO_ARGS
;
6253 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6255 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6258 if (!session
[s
].opened
)
6261 idle
= time_now
- session
[s
].last_data
;
6262 idle
/= 5 ; // In multiples of 5 seconds.
6272 for (i
= 0; i
< 63; ++i
)
6274 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6276 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6277 cli_print(cli
, "%d total sessions open.", count
);
6281 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6287 if (CLI_HELP_REQUESTED
)
6288 return CLI_HELP_NO_ARGS
;
6291 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6293 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6296 if (!session
[s
].opened
)
6299 d
= time_now
- session
[s
].opened
;
6302 while (d
> 1 && open
< 32)
6312 for (i
= 0; i
< 30; ++i
)
6314 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6317 cli_print(cli
, "%d total sessions open.", count
);
6323 * This unencodes the AVP using the L2TP secret and the previously
6324 * stored random vector. It overwrites the hidden data with the
6325 * unhidden AVP subformat.
6327 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6333 uint16_t m
= htons(type
);
6335 // Compute initial pad
6337 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6338 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6339 MD5_Update(&ctx
, vector
, vec_len
);
6340 MD5_Final(digest
, &ctx
);
6342 // pointer to last decoded 16 octets
6347 // calculate a new pad based on the last decoded block
6348 if (d
>= sizeof(digest
))
6351 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6352 MD5_Update(&ctx
, last
, sizeof(digest
));
6353 MD5_Final(digest
, &ctx
);
6359 *value
++ ^= digest
[d
++];
6364 int find_filter(char const *name
, size_t len
)
6369 for (i
= 0; i
< MAXFILTER
; i
++)
6371 if (!*ip_filters
[i
].name
)
6379 if (strlen(ip_filters
[i
].name
) != len
)
6382 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6389 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6393 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6394 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6395 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6396 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6397 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6403 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6407 case FILTER_FLAG_OP_ANY
:
6408 return (flags
& sflags
) || (~flags
& cflags
);
6410 case FILTER_FLAG_OP_ALL
:
6411 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6413 case FILTER_FLAG_OP_EST
:
6414 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6420 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6422 uint16_t frag_offset
;
6426 uint16_t src_port
= 0;
6427 uint16_t dst_port
= 0;
6429 ip_filter_rulet
*rule
;
6431 if (len
< 20) // up to end of destination address
6434 if ((*buf
>> 4) != 4) // IPv4
6437 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6439 src_ip
= *(in_addr_t
*) (buf
+ 12);
6440 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6442 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6444 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6445 if (len
< l
+ 4) // ports
6448 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6449 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6450 if (proto
== IPPROTO_TCP
)
6452 if (len
< l
+ 14) // flags
6455 flags
= buf
[l
+ 13] & 0x3f;
6459 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6461 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6464 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6465 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6468 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6469 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6474 // layer 4 deny rules are skipped
6475 if (rule
->action
== FILTER_ACTION_DENY
&&
6476 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6484 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6486 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6489 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6492 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6493 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6500 return rule
->action
== FILTER_ACTION_PERMIT
;
6507 tunnelidt
lac_new_tunnel()
6509 return new_tunnel();
6512 void lac_tunnelclear(tunnelidt t
)
6517 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6519 uint16_t version
= 0x0100; // protocol version
6521 tunnel
[t
].state
= TUNNELOPENING
;
6523 // Sent SCCRQ - Start Control Connection Request
6524 controlt
*c
= controlnew(1); // sending SCCRQ
6525 controls(c
, 7, hostname
, 1); // host name
6526 controls(c
, 8, Vendor_name
, 1); // Vendor name
6527 control16(c
, 2, version
, 1); // protocol version
6528 control32(c
, 3, 3, 1); // framing Capabilities
6529 control16(c
, 9, t
, 1); // assigned tunnel
6530 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6531 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6532 controladd(c
, 0, t
); // send
6535 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6537 // Sent ICRQ Incoming-call-request
6538 controlt
*c
= controlnew(10); // ICRQ
6540 control16(c
, 14, s
, 1); // assigned sesion
6541 call_serial_number
++;
6542 control32(c
, 15, call_serial_number
, 1); // call serial number
6543 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6544 controladd(c
, 0, t
); // send
6547 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6549 tunnelshutdown(t
, reason
, result
, error
, msg
);