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"
61 char * Vendor_name
= "Linux L2TPNS";
62 uint32_t call_serial_number
= 0;
66 configt
*config
= NULL
; // all configuration
67 int nlfd
= -1; // netlink socket
68 int tunfd
= -1; // tun interface file handle. (network device)
69 int udpfd
= -1; // UDP file handle
71 int udplacfd
= -1; // UDP LAC file handle
73 int controlfd
= -1; // Control signal handle
74 int clifd
= -1; // Socket listening for CLI connections.
75 int daefd
= -1; // Socket listening for DAE connections.
76 int snoopfd
= -1; // UDP file handle for sending out intercept data
77 int *radfds
= NULL
; // RADIUS requests file handles
78 int rand_fd
= -1; // Random data source
79 int cluster_sockfd
= -1; // Intra-cluster communications socket.
80 int epollfd
= -1; // event polling
81 time_t basetime
= 0; // base clock
82 char hostname
[MAXHOSTNAME
] = ""; // us.
83 static int tunidx
; // ifr_ifindex of tun device
84 int nlseqnum
= 0; // netlink sequence number
85 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
86 static int syslog_log
= 0; // are we logging to syslog
87 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
88 uint32_t last_id
= 0; // Unique ID for radius accounting
90 char guest_users
[10][32]; // Array of guest users
91 int guest_accounts_num
= 0; // Number of guest users
93 // calculated from config->l2tp_mtu
94 uint16_t MRU
= 0; // PPP MRU
95 uint16_t MSS
= 0; // TCP MSS
97 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
98 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
103 } ip_hash
[256]; // Mapping from IP address to session structures.
107 struct ipv6radix
*branch
;
108 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
111 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
112 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
115 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
116 time_t time_now
= 0; // Current time in seconds since epoch.
117 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
118 static char time_now_string
[64] = {0}; // Current time as a string.
119 static int time_changed
= 0; // time_now changed
120 char main_quit
= 0; // True if we're in the process of exiting.
121 static char main_reload
= 0; // Re-load pending
122 linked_list
*loaded_plugins
;
123 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
125 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
126 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
128 config_descriptt config_values
[] = {
129 CONFIG("debug", debug
, INT
),
130 CONFIG("log_file", log_filename
, STRING
),
131 CONFIG("pid_file", pid_file
, STRING
),
132 CONFIG("random_device", random_device
, STRING
),
133 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
134 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
135 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
136 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
137 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
138 CONFIG("primary_dns", default_dns1
, IPv4
),
139 CONFIG("secondary_dns", default_dns2
, IPv4
),
140 CONFIG("primary_radius", radiusserver
[0], IPv4
),
141 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
142 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
143 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
144 CONFIG("radius_accounting", radius_accounting
, BOOL
),
145 CONFIG("radius_interim", radius_interim
, INT
),
146 CONFIG("radius_secret", radiussecret
, STRING
),
147 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
148 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
149 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
150 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
151 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
152 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
153 CONFIG("guest_account", guest_user
, STRING
),
154 CONFIG("bind_address", bind_address
, IPv4
),
155 CONFIG("peer_address", peer_address
, IPv4
),
156 CONFIG("send_garp", send_garp
, BOOL
),
157 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
158 CONFIG("throttle_buckets", num_tbfs
, INT
),
159 CONFIG("accounting_dir", accounting_dir
, STRING
),
160 CONFIG("dump_speed", dump_speed
, BOOL
),
161 CONFIG("multi_read_count", multi_read_count
, INT
),
162 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
163 CONFIG("lock_pages", lock_pages
, BOOL
),
164 CONFIG("icmp_rate", icmp_rate
, INT
),
165 CONFIG("packet_limit", max_packets
, INT
),
166 CONFIG("cluster_address", cluster_address
, IPv4
),
167 CONFIG("cluster_interface", cluster_interface
, STRING
),
168 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
169 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
170 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
171 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
172 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
173 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
174 CONFIG("hostname", hostname
, STRING
),
176 CONFIG("nexthop_address", nexthop_address
, IPv4
),
177 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
179 CONFIG("echo_timeout", echo_timeout
, INT
),
180 CONFIG("idle_echo_timeout", idle_echo_timeout
, INT
),
181 CONFIG("iftun_address", iftun_address
, IPv4
),
182 CONFIG("tundevicename", tundevicename
, STRING
),
184 CONFIG("disable_lac_func", disable_lac_func
, BOOL
),
185 CONFIG("auth_tunnel_change_addr_src", auth_tunnel_change_addr_src
, BOOL
),
186 CONFIG("bind_address_remotelns", bind_address_remotelns
, IPv4
),
187 CONFIG("bind_portremotelns", bind_portremotelns
, SHORT
),
192 static char *plugin_functions
[] = {
197 "plugin_new_session",
198 "plugin_kill_session",
200 "plugin_radius_response",
201 "plugin_radius_reset",
202 "plugin_radius_account",
203 "plugin_become_master",
204 "plugin_new_session_master",
207 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
209 // Counters for shutdown sessions
210 static sessiont shut_acct
[8192];
211 static sessionidt shut_acct_n
= 0;
213 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
214 bundlet
*bundle
= NULL
; // Array of bundle structures.
215 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
216 sessiont
*session
= NULL
; // Array of session structures.
217 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
218 radiust
*radius
= NULL
; // Array of radius structures.
219 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
220 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
221 static controlt
*controlfree
= 0;
222 struct Tstats
*_statistics
= NULL
;
224 struct Tringbuffer
*ringbuffer
= NULL
;
227 static ssize_t
netlink_send(struct nlmsghdr
*nh
);
228 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
);
229 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
230 static void uncache_ipmap(in_addr_t ip
);
231 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
232 static void free_ip_address(sessionidt s
);
233 static void dump_acct_info(int all
);
234 static void sighup_handler(int sig
);
235 static void shutdown_handler(int sig
);
236 static void sigchild_handler(int sig
);
237 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
238 static void update_config(void);
239 static void read_config_file(void);
240 static void initplugins(void);
241 static int add_plugin(char *plugin_name
);
242 static int remove_plugin(char *plugin_name
);
243 static void plugins_done(void);
244 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
245 static tunnelidt
new_tunnel(void);
246 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
247 static void bundleclear(bundleidt b
);
249 // return internal time (10ths since process startup), set f if given
250 // as a side-effect sets time_now, and time_changed
251 static clockt
now(double *f
)
255 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
256 if (t
.tv_sec
!= time_now
)
262 // Time in milliseconds
263 // TODO FOR MLPPP DEV
264 //time_now_ms = (t.tv_sec * 1000) + (t.tv_usec/1000);
266 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
269 // work out a retry time based on try number
270 // This is a straight bounded exponential backoff.
271 // Maximum re-try time is 32 seconds. (2^5).
272 clockt
backoff(uint8_t try)
274 if (try > 5) try = 5; // max backoff
275 return now(NULL
) + 10 * (1 << try);
280 // Log a debug message. Typically called via the LOG macro
282 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
284 static char message
[65536] = {0};
290 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
291 ringbuffer
->tail
= 0;
292 if (ringbuffer
->tail
== ringbuffer
->head
)
293 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
294 ringbuffer
->head
= 0;
296 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
297 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
298 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
299 va_start(ap
, format
);
300 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, MAX_LOG_LENGTH
, format
, ap
);
305 if (config
->debug
< level
) return;
307 va_start(ap
, format
);
308 vsnprintf(message
, sizeof(message
), format
, ap
);
311 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
313 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
318 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
321 const uint8_t *d
= data
;
323 if (config
->debug
< level
) return;
325 // No support for _log_hex to syslog
328 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
329 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
331 for (i
= 0; i
< maxsize
; )
333 fprintf(log_stream
, "%4X: ", i
);
334 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
336 fprintf(log_stream
, "%02X ", d
[j
]);
338 fputs(": ", log_stream
);
341 for (; j
< i
+ 16; j
++)
343 fputs(" ", log_stream
);
345 fputs(": ", log_stream
);
348 fputs(" ", log_stream
);
349 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
351 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
352 fputc(d
[j
], log_stream
);
354 fputc('.', log_stream
);
357 fputs(" ", log_stream
);
361 fputs("\n", log_stream
);
365 setbuf(log_stream
, NULL
);
369 // update a counter, accumulating 2^32 wraps
370 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
372 uint32_t new = *counter
+ delta
;
379 // initialise the random generator
380 static void initrandom(char *source
)
382 static char path
[sizeof(config
->random_device
)] = "*undefined*";
384 // reinitialise only if we are forced to do so or if the config has changed
385 if (source
&& !strncmp(path
, source
, sizeof(path
)))
388 // close previous source, if any
397 snprintf(path
, sizeof(path
), "%s", source
);
401 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
403 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
404 path
, strerror(errno
));
409 // fill buffer with random data
410 void random_data(uint8_t *buf
, int len
)
417 n
= read(rand_fd
, buf
, len
);
418 if (n
>= len
) return;
423 LOG(0, 0, 0, "Error reading from random source: %s\n",
426 // fall back to rand()
434 // append missing data
436 // not using the low order bits from the prng stream
437 buf
[n
++] = (rand() >> 4) & 0xff;
442 // This adds it to the routing table, advertises it
443 // via BGP if enabled, and stuffs it into the
444 // 'sessionbyip' cache.
446 // 'ip' must be in _host_ order.
448 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
458 if (!prefixlen
) prefixlen
= 32;
460 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
462 memset(&req
, 0, sizeof(req
));
466 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
467 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
471 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
472 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
475 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
477 req
.rt
.rtm_family
= AF_INET
;
478 req
.rt
.rtm_dst_len
= prefixlen
;
479 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
480 req
.rt
.rtm_protocol
= 42;
481 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
482 req
.rt
.rtm_type
= RTN_UNICAST
;
484 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
486 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
490 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
493 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
494 fmtaddr(htonl(ip
), 0), prefixlen
,
495 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
497 if (netlink_send(&req
.nh
) < 0)
498 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
502 bgp_add_route(htonl(ip
), prefixlen
);
504 bgp_del_route(htonl(ip
), prefixlen
);
507 // Add/Remove the IPs to the 'sessionbyip' cache.
508 // Note that we add the zero address in the case of
509 // a network route. Roll on CIDR.
511 // Note that 's == 0' implies this is the address pool.
512 // We still cache it here, because it will pre-fill
513 // the malloc'ed tree.
517 if (!add
) // Are we deleting a route?
518 s
= 0; // Caching the session as '0' is the same as uncaching.
520 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
525 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
533 char ipv6addr
[INET6_ADDRSTRLEN
];
535 if (!config
->ipv6_prefix
.s6_addr
[0])
537 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
541 memset(&req
, 0, sizeof(req
));
545 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
546 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
550 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
551 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
554 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
556 req
.rt
.rtm_family
= AF_INET6
;
557 req
.rt
.rtm_dst_len
= prefixlen
;
558 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
559 req
.rt
.rtm_protocol
= 42;
560 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
561 req
.rt
.rtm_type
= RTN_UNICAST
;
563 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
564 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
566 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
568 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
570 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
573 if (netlink_send(&req
.nh
) < 0)
574 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
578 bgp_add_route6(ip
, prefixlen
);
580 bgp_del_route6(ip
, prefixlen
);
585 if (!add
) // Are we deleting a route?
586 s
= 0; // Caching the session as '0' is the same as uncaching.
588 cache_ipv6map(ip
, prefixlen
, s
);
595 // Set up netlink socket
596 static void initnetlink(void)
598 struct sockaddr_nl nladdr
;
600 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
603 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
607 memset(&nladdr
, 0, sizeof(nladdr
));
608 nladdr
.nl_family
= AF_NETLINK
;
609 nladdr
.nl_pid
= getpid();
611 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
613 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
618 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
620 struct sockaddr_nl nladdr
;
624 nh
->nlmsg_pid
= getpid();
625 nh
->nlmsg_seq
= ++nlseqnum
;
627 // set kernel address
628 memset(&nladdr
, 0, sizeof(nladdr
));
629 nladdr
.nl_family
= AF_NETLINK
;
631 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
632 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
634 return sendmsg(nlfd
, &msg
, 0);
637 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
639 struct sockaddr_nl nladdr
;
643 // set kernel address
644 memset(&nladdr
, 0, sizeof(nladdr
));
645 nladdr
.nl_family
= AF_NETLINK
;
647 iov
= (struct iovec
){ buf
, len
};
648 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
650 return recvmsg(nlfd
, &msg
, 0);
653 /* adapted from iproute2 */
654 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
656 int len
= RTA_LENGTH(alen
);
659 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
660 rta
->rta_type
= type
;
662 memcpy(RTA_DATA(rta
), data
, alen
);
663 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
666 // messages corresponding to different phases seq number
667 static char *tun_nl_phase_msg
[] = {
669 "getting tun interface index",
670 "setting tun interface parameters",
671 "setting tun IPv4 address",
672 "setting tun LL IPv6 address",
673 "setting tun global IPv6 address",
677 // Set up TUN interface
678 static void inittun(void)
682 memset(&ifr
, 0, sizeof(ifr
));
683 ifr
.ifr_flags
= IFF_TUN
;
685 tunfd
= open(TUNDEVICE
, O_RDWR
);
688 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
692 int flags
= fcntl(tunfd
, F_GETFL
, 0);
693 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
696 if (*config
->tundevicename
)
697 strncpy(ifr
.ifr_name
, config
->tundevicename
, IFNAMSIZ
);
699 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
701 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
704 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevicename
) - 1);
705 strncpy(config
->tundevicename
, ifr
.ifr_name
, sizeof(config
->tundevicename
));
707 tunidx
= if_nametoindex(config
->tundevicename
);
710 LOG(0, 0, 0, "Can't get tun interface index\n");
719 struct ifinfomsg ifinfo
;
720 struct ifaddrmsg ifaddr
;
722 char rtdata
[32]; // 32 should be enough
724 uint32_t txqlen
, mtu
;
727 memset(&req
, 0, sizeof(req
));
729 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
730 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
731 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
733 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
734 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
735 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
736 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
738 /* Bump up the qlen to deal with bursts from the network */
740 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
741 /* set MTU to modem MRU */
743 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
745 if (netlink_send(&req
.nh
) < 0)
748 memset(&req
, 0, sizeof(req
));
750 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
751 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
752 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
754 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
755 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
756 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
757 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
759 if (config
->iftun_address
)
760 ip
= config
->iftun_address
;
762 ip
= 0x01010101; // 1.1.1.1
763 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
765 if (netlink_send(&req
.nh
) < 0)
768 // Only setup IPv6 on the tun device if we have a configured prefix
769 if (config
->ipv6_prefix
.s6_addr
[0]) {
772 memset(&req
, 0, sizeof(req
));
774 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
775 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
776 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
778 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
779 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
780 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
781 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
783 // Link local address is FE80::1
784 memset(&ip6
, 0, sizeof(ip6
));
785 ip6
.s6_addr
[0] = 0xFE;
786 ip6
.s6_addr
[1] = 0x80;
788 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
790 if (netlink_send(&req
.nh
) < 0)
793 memset(&req
, 0, sizeof(req
));
795 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
796 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
797 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
799 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
800 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
801 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
802 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
804 // Global address is prefix::1
805 ip6
= config
->ipv6_prefix
;
807 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
809 if (netlink_send(&req
.nh
) < 0)
813 memset(&req
, 0, sizeof(req
));
815 req
.nh
.nlmsg_type
= NLMSG_DONE
;
816 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
818 if (netlink_send(&req
.nh
) < 0)
821 // if we get an error for seqnum < min_initok_nlseqnum,
822 // we must exit as initialization went wrong
823 if (config
->ipv6_prefix
.s6_addr
[0])
824 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
826 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
832 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
837 static void initudp(void)
840 struct sockaddr_in addr
;
843 memset(&addr
, 0, sizeof(addr
));
844 addr
.sin_family
= AF_INET
;
845 addr
.sin_port
= htons(L2TPPORT
);
846 addr
.sin_addr
.s_addr
= config
->bind_address
;
847 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
848 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
850 int flags
= fcntl(udpfd
, F_GETFL
, 0);
851 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
853 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
855 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
860 memset(&addr
, 0, sizeof(addr
));
861 addr
.sin_family
= AF_INET
;
862 addr
.sin_port
= htons(NSCTL_PORT
);
863 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
864 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
865 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
866 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
868 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
872 // Dynamic Authorization Extensions to RADIUS
873 memset(&addr
, 0, sizeof(addr
));
874 addr
.sin_family
= AF_INET
;
875 addr
.sin_port
= htons(config
->radius_dae_port
);
876 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
877 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
878 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
879 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
881 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
886 // Tunnel to Remote LNS
887 memset(&addr
, 0, sizeof(addr
));
888 addr
.sin_family
= AF_INET
;
889 addr
.sin_port
= htons(config
->bind_portremotelns
);
890 addr
.sin_addr
.s_addr
= config
->bind_address_remotelns
;
891 udplacfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
892 setsockopt(udplacfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
894 int flags
= fcntl(udplacfd
, F_GETFL
, 0);
895 fcntl(udplacfd
, F_SETFL
, flags
| O_NONBLOCK
);
897 if (bind(udplacfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
899 LOG(0, 0, 0, "Error in UDP REMOTE LNS bind: %s\n", strerror(errno
));
905 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
909 // Find session by IP, < 1 for not found
911 // Confusingly enough, this 'ip' must be
912 // in _network_ order. This being the common
913 // case when looking it up from IP packet headers.
915 // We actually use this cache for two things.
916 // #1. For used IP addresses, this maps to the
917 // session ID that it's used by.
918 // #2. For un-used IP addresses, this maps to the
919 // index into the pool table that contains that
923 static sessionidt
lookup_ipmap(in_addr_t ip
)
925 uint8_t *a
= (uint8_t *) &ip
;
926 union iphash
*h
= ip_hash
;
928 if (!(h
= h
[*a
++].idx
)) return 0;
929 if (!(h
= h
[*a
++].idx
)) return 0;
930 if (!(h
= h
[*a
++].idx
)) return 0;
935 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
937 struct ipv6radix
*curnode
;
940 char ipv6addr
[INET6_ADDRSTRLEN
];
942 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
946 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
948 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
953 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
954 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
961 sessionidt
sessionbyip(in_addr_t ip
)
963 sessionidt s
= lookup_ipmap(ip
);
966 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
972 sessionidt
sessionbyipv6(struct in6_addr ip
)
975 CSTAT(sessionbyipv6
);
977 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
978 (ip
.s6_addr
[0] == 0xFE &&
979 ip
.s6_addr
[1] == 0x80 &&
980 ip
.s6_addr16
[1] == 0 &&
981 ip
.s6_addr16
[2] == 0 &&
982 ip
.s6_addr16
[3] == 0)) {
983 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
985 s
= lookup_ipv6map(ip
);
988 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
995 // Take an IP address in HOST byte order and
996 // add it to the sessionid by IP cache.
998 // (It's actually cached in network order)
1000 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
1002 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
1003 uint8_t *a
= (uint8_t *) &nip
;
1004 union iphash
*h
= ip_hash
;
1007 for (i
= 0; i
< 3; i
++)
1009 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1018 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1021 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1022 // else a map to an ip pool index.
1025 static void uncache_ipmap(in_addr_t ip
)
1027 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1030 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1034 struct ipv6radix
*curnode
;
1035 char ipv6addr
[INET6_ADDRSTRLEN
];
1037 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
1039 bytes
= prefixlen
>> 3;
1042 if (curnode
->branch
== NULL
)
1044 if (!(curnode
->branch
= calloc(256,
1045 sizeof (struct ipv6radix
))))
1048 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1055 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1056 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1060 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1061 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1067 // CLI list to dump current ipcache.
1069 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1071 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1075 if (CLI_HELP_REQUESTED
)
1076 return CLI_HELP_NO_ARGS
;
1078 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1080 for (i
= 0; i
< 256; ++i
)
1086 for (j
= 0; j
< 256; ++j
)
1092 for (k
= 0; k
< 256; ++k
)
1098 for (l
= 0; l
< 256; ++l
)
1103 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1109 cli_print(cli
, "%d entries in cache", count
);
1114 // Find session by username, 0 for not found
1115 // walled garden users aren't authenticated, so the username is
1116 // reasonably useless. Ignore them to avoid incorrect actions
1118 // This is VERY inefficent. Don't call it often. :)
1120 sessionidt
sessionbyuser(char *username
)
1123 CSTAT(sessionbyuser
);
1125 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1127 if (!session
[s
].opened
)
1130 if (session
[s
].walled_garden
)
1131 continue; // Skip walled garden users.
1133 if (!strncmp(session
[s
].user
, username
, 128))
1137 return 0; // Not found.
1140 void send_garp(in_addr_t ip
)
1146 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1149 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1152 memset(&ifr
, 0, sizeof(ifr
));
1153 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1154 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1156 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1160 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1161 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1163 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1168 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1171 static sessiont
*sessiontbysessionidt(sessionidt s
)
1173 if (!s
|| s
>= MAXSESSION
) return NULL
;
1177 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1179 sessionidt val
= s
-session
;
1180 if (s
< session
|| val
>= MAXSESSION
) return 0;
1184 // actually send a control message for a specific tunnel
1185 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1187 struct sockaddr_in addr
;
1193 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1194 STAT(tunnel_tx_errors
);
1200 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1201 STAT(tunnel_tx_errors
);
1205 memset(&addr
, 0, sizeof(addr
));
1206 addr
.sin_family
= AF_INET
;
1207 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1208 addr
.sin_port
= htons(tunnel
[t
].port
);
1210 // sequence expected, if sequence in message
1211 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1213 // If this is a control message, deal with retries
1216 tunnel
[t
].last
= time_now
; // control message sent
1217 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1220 STAT(tunnel_retries
);
1221 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1225 if (sendto((tunnel
[t
].isremotelns
?udplacfd
:udpfd
), buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1227 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1230 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1231 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1232 STAT(tunnel_tx_errors
);
1236 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1237 STAT(tunnel_tx_packets
);
1238 INC_STAT(tunnel_tx_bytes
, l
);
1242 // Tiny helper function to write data to
1243 // the 'tun' device.
1245 int tun_write(uint8_t * data
, int size
)
1247 return write(tunfd
, data
, size
);
1250 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1251 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1253 int d
= (tcp
[12] >> 4) * 4;
1260 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1263 if (tcp
+ d
> buf
+ len
) // short?
1271 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1274 if (mss
+ 2 > data
) return; // short?
1278 if (*opts
== 0) return; // end of options
1279 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1282 opts
+= opts
[1]; // skip over option
1285 if (!mss
) return; // not found
1286 orig
= ntohs(*(uint16_t *) mss
);
1288 if (orig
<= MSS
) return; // mss OK
1290 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1291 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1292 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1293 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1296 *(int16_t *) mss
= htons(MSS
);
1298 // adjust checksum (see rfc1141)
1299 sum
= orig
+ (~MSS
& 0xffff);
1300 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1301 sum
= (sum
& 0xffff) + (sum
>> 16);
1302 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1305 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1309 // Skip the four extra bytes
1321 proto
= ntohs(*(uint16_t *) p
);
1329 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1330 return; // closing session, PPP not processed
1332 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1333 processipin(s
, t
, p
, l
);
1335 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1339 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1340 return; // closing session, PPP not processed
1343 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1344 processipv6in(s
, t
, p
, l
);
1346 else if (proto
== PPPIPCP
)
1348 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1349 processipcp(s
, t
, p
, l
);
1351 else if (proto
== PPPCCP
)
1353 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1354 processccp(s
, t
, p
, l
);
1358 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1362 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1364 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1365 sp
->cout_delta
+= len
;
1367 sp
->last_data
= time_now
;
1369 sess_local
[s
].cout
+= len
; // To send to master..
1370 sess_local
[s
].pout
++;
1373 // process outgoing (to tunnel) IP
1375 // (i.e. this routine writes to data[-8]).
1376 void processipout(uint8_t *buf
, int len
)
1383 uint8_t *data
= buf
; // Keep a copy of the originals.
1386 uint8_t fragbuf
[MAXETHER
+ 20];
1388 CSTAT(processipout
);
1390 if (len
< MIN_IP_SIZE
)
1392 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1393 STAT(tun_rx_errors
);
1396 if (len
>= MAXETHER
)
1398 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1399 STAT(tun_rx_errors
);
1403 // Skip the tun header
1407 // Got an IP header now
1408 if (*(uint8_t *)(buf
) >> 4 != 4)
1410 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1414 ip
= *(uint32_t *)(buf
+ 16);
1415 if (!(s
= sessionbyip(ip
)))
1417 // Is this a packet for a session that doesn't exist?
1418 static int rate
= 0; // Number of ICMP packets we've sent this second.
1419 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1421 if (last
!= time_now
)
1427 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1429 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1430 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1431 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1436 t
= session
[s
].tunnel
;
1437 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1439 LOG(3, s
, t
, "Packet size more than session MRU\n");
1445 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1446 if (config
->max_packets
> 0)
1448 if (sess_local
[s
].last_packet_out
== TIME
)
1450 int max
= config
->max_packets
;
1452 // All packets for throttled sessions are handled by the
1453 // master, so further limit by using the throttle rate.
1454 // A bit of a kludge, since throttle rate is in kbps,
1455 // but should still be generous given our average DSL
1456 // packet size is 200 bytes: a limit of 28kbps equates
1457 // to around 180 packets per second.
1458 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1459 max
= sp
->throttle_out
;
1461 if (++sess_local
[s
].packets_out
> max
)
1463 sess_local
[s
].packets_dropped
++;
1469 if (sess_local
[s
].packets_dropped
)
1471 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1472 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1473 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1474 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1478 sess_local
[s
].last_packet_out
= TIME
;
1479 sess_local
[s
].packets_out
= 1;
1480 sess_local
[s
].packets_dropped
= 0;
1484 // run access-list if any
1485 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1488 // adjust MSS on SYN and SYN,ACK packets with options
1489 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1491 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1492 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1493 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1498 // Are we throttling this session?
1499 if (config
->cluster_iam_master
)
1500 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1502 master_throttle_packet(sp
->tbf_out
, data
, size
);
1506 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1508 // We are walled-gardening this
1509 master_garden_packet(s
, data
, size
);
1513 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1516 if (!config
->cluster_iam_master
)
1518 // The MPPP packets must be managed by the Master.
1519 master_forward_mppp_packet(s
, data
, size
);
1523 // Add on L2TP header
1524 sessionidt members
[MAXBUNDLESES
];
1525 bundleidt bid
= session
[s
].bundle
;
1526 bundlet
*b
= &bundle
[bid
];
1527 uint32_t num_of_links
, nb_opened
;
1530 num_of_links
= b
->num_of_links
;
1532 for (i
= 0;i
< num_of_links
;i
++)
1535 if (session
[s
].ppp
.lcp
== Opened
)
1537 members
[nb_opened
] = s
;
1544 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1548 num_of_links
= nb_opened
;
1549 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1550 s
= members
[b
->current_ses
];
1551 t
= session
[s
].tunnel
;
1553 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1555 if (num_of_links
> 1)
1557 if(len
> MINFRAGLEN
)
1559 //for rotate traffic among the member links
1560 uint32_t divisor
= num_of_links
;
1562 divisor
= divisor
/2 + (divisor
& 1);
1564 // Partition the packet to "num_of_links" fragments
1565 uint32_t fraglen
= len
/ divisor
;
1566 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1567 uint32_t remain
= len
;
1569 // send the first packet
1570 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1572 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1575 update_session_out_stat(s
, sp
, fraglen
);
1578 while (remain
> last_fraglen
)
1580 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1581 s
= members
[b
->current_ses
];
1582 t
= session
[s
].tunnel
;
1584 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1585 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1587 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1588 update_session_out_stat(s
, sp
, fraglen
);
1591 // send the last fragment
1592 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1593 s
= members
[b
->current_ses
];
1594 t
= session
[s
].tunnel
;
1596 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1597 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1599 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1600 update_session_out_stat(s
, sp
, remain
);
1601 if (remain
!= last_fraglen
)
1602 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1606 // Send it as one frame
1607 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1609 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1610 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1611 update_session_out_stat(s
, sp
, len
);
1616 // Send it as one frame (NO MPPP Frame)
1617 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1619 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1620 update_session_out_stat(s
, sp
, len
);
1625 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1627 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1628 update_session_out_stat(s
, sp
, len
);
1631 // Snooping this session, send it to intercept box
1632 if (sp
->snoop_ip
&& sp
->snoop_port
)
1633 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1638 // process outgoing (to tunnel) IPv6
1640 static void processipv6out(uint8_t * buf
, int len
)
1646 struct in6_addr ip6
;
1648 uint8_t *data
= buf
; // Keep a copy of the originals.
1651 uint8_t b
[MAXETHER
+ 20];
1653 CSTAT(processipv6out
);
1655 if (len
< MIN_IP_SIZE
)
1657 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1658 STAT(tunnel_tx_errors
);
1661 if (len
>= MAXETHER
)
1663 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1664 STAT(tunnel_tx_errors
);
1668 // Skip the tun header
1672 // Got an IP header now
1673 if (*(uint8_t *)(buf
) >> 4 != 6)
1675 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1679 ip6
= *(struct in6_addr
*)(buf
+24);
1680 s
= sessionbyipv6(ip6
);
1684 ip
= *(uint32_t *)(buf
+ 32);
1685 s
= sessionbyip(ip
);
1690 // Is this a packet for a session that doesn't exist?
1691 static int rate
= 0; // Number of ICMP packets we've sent this second.
1692 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1694 if (last
!= time_now
)
1700 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1702 // FIXME: Should send icmp6 host unreachable
1706 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1708 bundleidt bid
= session
[s
].bundle
;
1709 bundlet
*b
= &bundle
[bid
];
1711 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1712 s
= b
->members
[b
->current_ses
];
1713 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1715 t
= session
[s
].tunnel
;
1717 sp
->last_data
= time_now
;
1719 // FIXME: add DoS prevention/filters?
1723 // Are we throttling this session?
1724 if (config
->cluster_iam_master
)
1725 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1727 master_throttle_packet(sp
->tbf_out
, data
, size
);
1730 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1732 // We are walled-gardening this
1733 master_garden_packet(s
, data
, size
);
1737 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1739 // Add on L2TP header
1741 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1743 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1746 // Snooping this session, send it to intercept box
1747 if (sp
->snoop_ip
&& sp
->snoop_port
)
1748 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1750 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1751 sp
->cout_delta
+= len
;
1755 sess_local
[s
].cout
+= len
; // To send to master..
1756 sess_local
[s
].pout
++;
1760 // Helper routine for the TBF filters.
1761 // Used to send queued data in to the user!
1763 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1768 uint8_t b
[MAXETHER
+ 20];
1770 if (len
< 0 || len
> MAXETHER
)
1772 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1776 // Skip the tun header
1783 t
= session
[s
].tunnel
;
1786 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1788 // Add on L2TP header
1790 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1792 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1795 // Snooping this session.
1796 if (sp
->snoop_ip
&& sp
->snoop_port
)
1797 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1799 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1800 sp
->cout_delta
+= len
;
1804 sess_local
[s
].cout
+= len
; // To send to master..
1805 sess_local
[s
].pout
++;
1808 // add an AVP (16 bit)
1809 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1811 uint16_t l
= (m
? 0x8008 : 0x0008);
1812 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1813 c
->buf16
[c
->length
/2 + 1] = htons(0);
1814 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1815 c
->buf16
[c
->length
/2 + 3] = htons(val
);
1819 // add an AVP (32 bit)
1820 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1822 uint16_t l
= (m
? 0x800A : 0x000A);
1823 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1824 c
->buf16
[c
->length
/2 + 1] = htons(0);
1825 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1826 *(uint32_t *) &c
->buf
[c
->length
+ 6] = htonl(val
);
1830 // add an AVP (string)
1831 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1833 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1834 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1835 c
->buf16
[c
->length
/2 + 1] = htons(0);
1836 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1837 memcpy(&c
->buf
[c
->length
+ 6], val
, strlen(val
));
1838 c
->length
+= 6 + strlen(val
);
1842 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1844 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1845 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1846 c
->buf16
[c
->length
/2 + 1] = htons(0);
1847 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1848 memcpy(&c
->buf
[c
->length
+ 6], val
, len
);
1849 c
->length
+= 6 + len
;
1852 // new control connection
1853 static controlt
*controlnew(uint16_t mtype
)
1857 c
= malloc(sizeof(controlt
));
1861 controlfree
= c
->next
;
1865 c
->buf16
[0] = htons(0xC802); // flags/ver
1867 control16(c
, 0, mtype
, 1);
1871 // send zero block if nothing is waiting
1873 static void controlnull(tunnelidt t
)
1876 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1879 buf
[0] = htons(0xC802); // flags/ver
1880 buf
[1] = htons(12); // length
1881 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1882 buf
[3] = htons(0); // session
1883 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1884 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1885 tunnelsend((uint8_t *)buf
, 12, t
);
1888 // add a control message to a tunnel, and send if within window
1889 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1891 c
->buf16
[1] = htons(c
->length
); // length
1892 c
->buf16
[2] = htons(tunnel
[t
].far
); // tunnel
1893 c
->buf16
[3] = htons(far
); // session
1894 c
->buf16
[4] = htons(tunnel
[t
].ns
); // sequence
1895 tunnel
[t
].ns
++; // advance sequence
1896 // link in message in to queue
1897 if (tunnel
[t
].controlc
)
1898 tunnel
[t
].controle
->next
= c
;
1900 tunnel
[t
].controls
= c
;
1902 tunnel
[t
].controle
= c
;
1903 tunnel
[t
].controlc
++;
1905 // send now if space in window
1906 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1908 tunnel
[t
].try = 0; // first send
1909 tunnelsend(c
->buf
, c
->length
, t
);
1914 // Throttle or Unthrottle a session
1916 // Throttle the data from/to through a session to no more than
1917 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1920 // If either value is -1, the current value is retained for that
1923 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1925 if (!session
[s
].opened
)
1926 return; // No-one home.
1928 if (!*session
[s
].user
)
1929 return; // User not logged in
1933 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1934 if (session
[s
].tbf_in
)
1935 free_tbf(session
[s
].tbf_in
);
1938 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1940 session
[s
].tbf_in
= 0;
1942 session
[s
].throttle_in
= rate_in
;
1947 int bytes
= rate_out
* 1024 / 8;
1948 if (session
[s
].tbf_out
)
1949 free_tbf(session
[s
].tbf_out
);
1952 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1954 session
[s
].tbf_out
= 0;
1956 session
[s
].throttle_out
= rate_out
;
1960 // add/remove filters from session (-1 = no change)
1961 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1963 if (!session
[s
].opened
)
1964 return; // No-one home.
1966 if (!*session
[s
].user
)
1967 return; // User not logged in
1970 if (filter_in
> MAXFILTER
) filter_in
= -1;
1971 if (filter_out
> MAXFILTER
) filter_out
= -1;
1972 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1973 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1977 if (session
[s
].filter_in
)
1978 ip_filters
[session
[s
].filter_in
- 1].used
--;
1981 ip_filters
[filter_in
- 1].used
++;
1983 session
[s
].filter_in
= filter_in
;
1986 if (filter_out
>= 0)
1988 if (session
[s
].filter_out
)
1989 ip_filters
[session
[s
].filter_out
- 1].used
--;
1992 ip_filters
[filter_out
- 1].used
++;
1994 session
[s
].filter_out
= filter_out
;
1998 // start tidy shutdown of session
1999 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
2001 int walled_garden
= session
[s
].walled_garden
;
2002 bundleidt b
= session
[s
].bundle
;
2003 //delete routes only for last session in bundle (in case of MPPP)
2004 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
2006 CSTAT(sessionshutdown
);
2008 if (!session
[s
].opened
)
2010 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2011 return; // not a live session
2014 if (!session
[s
].die
)
2016 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2017 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2018 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2019 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2022 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2024 // RADIUS Stop message
2025 uint16_t r
= radiusnew(s
);
2028 // stop, if not already trying
2029 if (radius
[r
].state
!= RADIUSSTOP
)
2031 radius
[r
].term_cause
= term_cause
;
2032 radius
[r
].term_msg
= reason
;
2033 radiussend(r
, RADIUSSTOP
);
2037 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2039 // Save counters to dump to accounting file
2040 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2041 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2045 { // IP allocated, clear and unroute
2048 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2050 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2051 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2054 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2055 session
[s
].route
[r
].ip
= 0;
2058 if (session
[s
].ip_pool_index
== -1) // static ip
2060 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2066 // unroute IPv6, if setup
2067 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
2068 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2072 // This session was part of a bundle
2073 bundle
[b
].num_of_links
--;
2074 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2075 if(bundle
[b
].num_of_links
== 0)
2078 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2082 // Adjust the members array to accomodate the new change
2083 uint8_t mem_num
= 0;
2084 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2085 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2088 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2089 if(bundle
[b
].members
[ml
] == s
)
2094 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2095 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2097 // If the killed session is the first of the bundle,
2098 // the new first session must be stored in the cache_ipmap
2099 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2102 sessionidt new_s
= bundle
[b
].members
[0];
2105 // Add the route for this session.
2106 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2111 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2112 ip
= session
[new_s
].route
[r
].ip
;
2114 if (!prefixlen
) prefixlen
= 32;
2115 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2117 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2118 cache_ipmap(i
, new_s
);
2120 cache_ipmap(session
[new_s
].ip
, new_s
);
2123 if (session
[new_s
].ipv6prefixlen
)
2124 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2129 cluster_send_bundle(b
);
2133 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2134 throttle_session(s
, 0, 0);
2138 controlt
*c
= controlnew(14); // sending CDN
2142 buf
[0] = htons(cdn_result
);
2143 buf
[1] = htons(cdn_error
);
2144 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2147 control16(c
, 1, cdn_result
, 1);
2149 control16(c
, 14, s
, 1); // assigned session (our end)
2150 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2153 // update filter refcounts
2154 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2155 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2158 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2159 sess_local
[s
].lcp
.restart
= 0;
2160 sess_local
[s
].ipcp
.restart
= 0;
2161 sess_local
[s
].ipv6cp
.restart
= 0;
2162 sess_local
[s
].ccp
.restart
= 0;
2164 cluster_send_session(s
);
2167 void sendipcp(sessionidt s
, tunnelidt t
)
2169 uint8_t buf
[MAXETHER
];
2173 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2175 if (!session
[s
].unique_id
)
2177 if (!++last_id
) ++last_id
; // skip zero
2178 session
[s
].unique_id
= last_id
;
2181 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2185 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2186 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2187 q
[4] = 3; // ip address option
2188 q
[5] = 6; // option length
2189 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2190 config
->iftun_address
? config
->iftun_address
:
2191 my_address
; // send my IP
2193 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2194 restart_timer(s
, ipcp
);
2197 void sendipv6cp(sessionidt s
, tunnelidt t
)
2199 uint8_t buf
[MAXETHER
];
2203 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2205 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2209 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2210 // only send one type
2212 *(uint16_t *) (q
+ 2) = htons(14);
2213 q
[4] = 1; // interface identifier option
2214 q
[5] = 10; // option length
2215 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2216 *(uint32_t *) (q
+ 10) = 0;
2219 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2220 restart_timer(s
, ipv6cp
);
2223 static void sessionclear(sessionidt s
)
2225 memset(&session
[s
], 0, sizeof(session
[s
]));
2226 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2227 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2229 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2230 session
[s
].next
= sessionfree
;
2234 // kill a session now
2235 void sessionkill(sessionidt s
, char *reason
)
2239 if (!session
[s
].opened
) // not alive
2242 if (session
[s
].next
)
2244 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2248 if (!session
[s
].die
)
2249 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2251 if (sess_local
[s
].radius
)
2252 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2255 if (session
[s
].forwardtosession
)
2257 sessionidt sess
= session
[s
].forwardtosession
;
2258 if (session
[sess
].forwardtosession
== s
)
2260 // Shutdown the linked session also.
2261 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2266 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2268 cluster_send_session(s
);
2271 static void tunnelclear(tunnelidt t
)
2274 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2275 tunnel
[t
].state
= TUNNELFREE
;
2278 static void bundleclear(bundleidt b
)
2281 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2282 bundle
[b
].state
= BUNDLEFREE
;
2285 // kill a tunnel now
2286 static void tunnelkill(tunnelidt t
, char *reason
)
2293 tunnel
[t
].state
= TUNNELDIE
;
2295 // free control messages
2296 while ((c
= tunnel
[t
].controls
))
2298 controlt
* n
= c
->next
;
2299 tunnel
[t
].controls
= n
;
2300 tunnel
[t
].controlc
--;
2301 c
->next
= controlfree
;
2305 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2306 if (session
[s
].tunnel
== t
)
2307 sessionkill(s
, reason
);
2311 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2312 cli_tunnel_actions
[t
].action
= 0;
2313 cluster_send_tunnel(t
);
2316 // shut down a tunnel cleanly
2317 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2321 CSTAT(tunnelshutdown
);
2323 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2325 // never set up, can immediately kill
2326 tunnelkill(t
, reason
);
2329 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2332 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2333 if (session
[s
].tunnel
== t
)
2334 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2336 tunnel
[t
].state
= TUNNELDIE
;
2337 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2338 cluster_send_tunnel(t
);
2339 // TBA - should we wait for sessions to stop?
2342 controlt
*c
= controlnew(4); // sending StopCCN
2347 buf
[0] = htons(result
);
2348 buf
[1] = htons(error
);
2351 int m
= strlen(msg
);
2352 if (m
+ 4 > sizeof(buf
))
2353 m
= sizeof(buf
) - 4;
2355 memcpy(buf
+2, msg
, m
);
2359 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2362 control16(c
, 1, result
, 1);
2364 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2365 controladd(c
, 0, t
); // send the message
2369 // read and process packet on tunnel (UDP)
2370 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2372 uint8_t *chapresponse
= NULL
;
2373 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2374 uint8_t *p
= buf
+ 2;
2381 LOG_HEX(5, "UDP Data", buf
, len
);
2382 STAT(tunnel_rx_packets
);
2383 INC_STAT(tunnel_rx_bytes
, len
);
2386 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2387 STAT(tunnel_rx_errors
);
2390 if ((buf
[1] & 0x0F) != 2)
2392 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2393 STAT(tunnel_rx_errors
);
2398 l
= ntohs(*(uint16_t *) p
);
2401 t
= ntohs(*(uint16_t *) p
);
2403 s
= ntohs(*(uint16_t *) p
);
2405 if (s
>= MAXSESSION
)
2407 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2408 STAT(tunnel_rx_errors
);
2413 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2414 STAT(tunnel_rx_errors
);
2419 ns
= ntohs(*(uint16_t *) p
);
2421 nr
= ntohs(*(uint16_t *) p
);
2426 uint16_t o
= ntohs(*(uint16_t *) p
);
2431 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2432 STAT(tunnel_rx_errors
);
2437 // used to time out old tunnels
2438 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2439 tunnel
[t
].lastrec
= time_now
;
2443 uint16_t message
= 0xFFFF; // message type
2445 uint8_t mandatory
= 0;
2446 uint16_t asession
= 0; // assigned session
2447 uint32_t amagic
= 0; // magic number
2448 uint8_t aflags
= 0; // flags from last LCF
2449 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2450 char called
[MAXTEL
] = ""; // called number
2451 char calling
[MAXTEL
] = ""; // calling number
2453 if (!config
->cluster_iam_master
)
2455 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2459 // control messages must have bits 0x80|0x40|0x08
2460 // (type, length and sequence) set, and bits 0x02|0x01
2461 // (offset and priority) clear
2462 if ((*buf
& 0xCB) != 0xC8)
2464 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2465 STAT(tunnel_rx_errors
);
2469 // check for duplicate tunnel open message
2475 // Is this a duplicate of the first packet? (SCCRQ)
2477 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2479 if (tunnel
[i
].state
!= TUNNELOPENING
||
2480 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2481 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2484 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2489 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2490 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2492 // if no tunnel specified, assign one
2495 if (!(t
= new_tunnel()))
2497 LOG(1, 0, 0, "No more tunnels\n");
2498 STAT(tunnel_overflow
);
2502 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2503 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2504 tunnel
[t
].window
= 4; // default window
2505 STAT(tunnel_created
);
2506 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2507 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2510 // If the 'ns' just received is not the 'nr' we're
2511 // expecting, just send an ack and drop it.
2513 // if 'ns' is less, then we got a retransmitted packet.
2514 // if 'ns' is greater than missed a packet. Either way
2515 // we should ignore it.
2516 if (ns
!= tunnel
[t
].nr
)
2518 // is this the sequence we were expecting?
2519 STAT(tunnel_rx_errors
);
2520 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2521 t
, ns
, tunnel
[t
].nr
);
2523 if (l
) // Is this not a ZLB?
2528 // check sequence of this message
2530 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2531 // some to clear maybe?
2532 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2534 controlt
*c
= tunnel
[t
].controls
;
2535 tunnel
[t
].controls
= c
->next
;
2536 tunnel
[t
].controlc
--;
2537 c
->next
= controlfree
;
2540 tunnel
[t
].try = 0; // we have progress
2543 // receiver advance (do here so quoted correctly in any sends below)
2544 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2545 if (skip
< 0) skip
= 0;
2546 if (skip
< tunnel
[t
].controlc
)
2548 // some control packets can now be sent that were previous stuck out of window
2549 int tosend
= tunnel
[t
].window
- skip
;
2550 controlt
*c
= tunnel
[t
].controls
;
2558 tunnel
[t
].try = 0; // first send
2559 tunnelsend(c
->buf
, c
->length
, t
);
2564 if (!tunnel
[t
].controlc
)
2565 tunnel
[t
].retry
= 0; // caught up
2568 { // if not a null message
2573 // Default disconnect cause/message on receipt of CDN. Set to
2574 // more specific value from attribute 1 (result code) or 46
2575 // (disconnect cause) if present below.
2576 int disc_cause_set
= 0;
2577 int disc_cause
= TERM_NAS_REQUEST
;
2578 char const *disc_reason
= "Closed (Received CDN).";
2581 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2583 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2590 LOG(1, s
, t
, "Invalid length in AVP\n");
2591 STAT(tunnel_rx_errors
);
2596 if (flags
& 0x3C) // reserved bits, should be clear
2598 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2600 result
= 2; // general error
2601 error
= 3; // reserved field non-zero
2606 if (*(uint16_t *) (b
))
2608 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2610 result
= 2; // general error
2611 error
= 6; // generic vendor-specific error
2612 msg
= "unsupported vendor-specific";
2616 mtype
= ntohs(*(uint16_t *) (b
));
2624 // handle hidden AVPs
2625 if (!*config
->l2tp_secret
)
2627 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2629 result
= 2; // general error
2630 error
= 6; // generic vendor-specific error
2631 msg
= "secret not specified";
2634 if (!session
[s
].random_vector_length
)
2636 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2638 result
= 2; // general error
2639 error
= 6; // generic
2640 msg
= "no random vector";
2645 LOG(2, s
, t
, "Short hidden AVP.\n");
2647 result
= 2; // general error
2648 error
= 2; // length is wrong
2654 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2656 orig_len
= ntohs(*(uint16_t *) b
);
2657 if (orig_len
> n
+ 2)
2659 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2663 result
= 2; // general error
2664 error
= 2; // length is wrong
2673 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2674 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2678 case 0: // message type
2679 message
= ntohs(*(uint16_t *) b
);
2680 mandatory
= flags
& 0x80;
2681 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2683 case 1: // result code
2685 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2686 char const *resdesc
= "(unknown)";
2687 char const *errdesc
= NULL
;
2692 resdesc
= l2tp_stopccn_result_code(rescode
);
2693 cause
= TERM_LOST_SERVICE
;
2695 else if (message
== 14)
2697 resdesc
= l2tp_cdn_result_code(rescode
);
2699 cause
= TERM_LOST_CARRIER
;
2701 cause
= TERM_ADMIN_RESET
;
2704 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2707 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2708 errdesc
= l2tp_error_code(errcode
);
2709 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2712 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2714 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2716 disc_cause_set
= mtype
;
2717 disc_reason
= errdesc
? errdesc
: resdesc
;
2724 case 2: // protocol version
2726 version
= ntohs(*(uint16_t *) (b
));
2727 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2728 if (version
&& version
!= 0x0100)
2729 { // allow 0.0 and 1.0
2730 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2732 result
= 5; // unspported protocol version
2733 error
= 0x0100; // supported version
2739 case 3: // framing capabilities
2741 case 4: // bearer capabilities
2743 case 5: // tie breaker
2744 // We never open tunnels, so we don't care about tie breakers
2746 case 6: // firmware revision
2748 case 7: // host name
2749 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2750 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2751 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2752 // TBA - to send to RADIUS
2754 case 8: // vendor name
2755 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2756 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2757 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2759 case 9: // assigned tunnel
2760 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2761 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2763 case 10: // rx window
2764 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2765 if (!tunnel
[t
].window
)
2766 tunnel
[t
].window
= 1; // window of 0 is silly
2767 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2769 case 11: // Challenge
2771 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2772 build_chap_response(b
, 2, n
, &chapresponse
);
2775 case 13: // Response
2777 if (tunnel
[t
].isremotelns
)
2779 chapresponse
= calloc(17, 1);
2780 memcpy(chapresponse
, b
, (n
< 17) ? n
: 16);
2781 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2785 // Why did they send a response? We never challenge.
2786 LOG(2, s
, t
, " received unexpected challenge response\n");
2789 case 14: // assigned session
2790 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2791 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2793 case 15: // call serial number
2794 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2796 case 18: // bearer type
2797 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2800 case 19: // framing type
2801 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2804 case 21: // called number
2805 memset(called
, 0, sizeof(called
));
2806 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2807 LOG(4, s
, t
, " Called <%s>\n", called
);
2809 case 22: // calling number
2810 memset(calling
, 0, sizeof(calling
));
2811 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2812 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2816 case 24: // tx connect speed
2819 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2823 // AS5300s send connect speed as a string
2825 memset(tmp
, 0, sizeof(tmp
));
2826 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2827 session
[s
].tx_connect_speed
= atol(tmp
);
2829 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2831 case 38: // rx connect speed
2834 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2838 // AS5300s send connect speed as a string
2840 memset(tmp
, 0, sizeof(tmp
));
2841 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2842 session
[s
].rx_connect_speed
= atol(tmp
);
2844 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2846 case 25: // Physical Channel ID
2848 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2849 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2852 case 29: // Proxy Authentication Type
2854 uint16_t atype
= ntohs(*(uint16_t *)b
);
2855 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2858 case 30: // Proxy Authentication Name
2861 memset(authname
, 0, sizeof(authname
));
2862 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2863 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2867 case 31: // Proxy Authentication Challenge
2869 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2872 case 32: // Proxy Authentication ID
2874 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2875 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2878 case 33: // Proxy Authentication Response
2879 LOG(4, s
, t
, " Proxy Auth Response\n");
2881 case 27: // last sent lcp
2882 { // find magic number
2883 uint8_t *p
= b
, *e
= p
+ n
;
2884 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2886 if (*p
== 5 && p
[1] == 6) // Magic-Number
2887 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2888 else if (*p
== 7) // Protocol-Field-Compression
2889 aflags
|= SESSION_PFC
;
2890 else if (*p
== 8) // Address-and-Control-Field-Compression
2891 aflags
|= SESSION_ACFC
;
2896 case 28: // last recv lcp confreq
2898 case 26: // Initial Received LCP CONFREQ
2900 case 39: // seq required - we control it as an LNS anyway...
2902 case 36: // Random Vector
2903 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2904 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2905 if (n
> sizeof(session
[s
].random_vector
))
2906 n
= sizeof(session
[s
].random_vector
);
2907 memcpy(session
[s
].random_vector
, b
, n
);
2908 session
[s
].random_vector_length
= n
;
2910 case 46: // ppp disconnect cause
2913 uint16_t code
= ntohs(*(uint16_t *) b
);
2914 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2915 uint8_t dir
= *(b
+ 4);
2917 LOG(4, s
, t
, " PPP disconnect cause "
2918 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2919 code
, proto
, dir
, n
- 5, b
+ 5);
2921 disc_cause_set
= mtype
;
2925 case 1: // admin disconnect
2926 disc_cause
= TERM_ADMIN_RESET
;
2927 disc_reason
= "Administrative disconnect";
2929 case 3: // lcp terminate
2930 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2931 disc_cause
= TERM_USER_REQUEST
;
2932 disc_reason
= "Normal disconnection";
2934 case 4: // compulsory encryption unavailable
2935 if (dir
!= 1) break; // 1=refused by peer, 2=local
2936 disc_cause
= TERM_USER_ERROR
;
2937 disc_reason
= "Compulsory encryption refused";
2939 case 5: // lcp: fsm timeout
2940 disc_cause
= TERM_PORT_ERROR
;
2941 disc_reason
= "LCP: FSM timeout";
2943 case 6: // lcp: no recognisable lcp packets received
2944 disc_cause
= TERM_PORT_ERROR
;
2945 disc_reason
= "LCP: no recognisable LCP packets";
2947 case 7: // lcp: magic-no error (possibly looped back)
2948 disc_cause
= TERM_PORT_ERROR
;
2949 disc_reason
= "LCP: magic-no error (possible loop)";
2951 case 8: // lcp: echo request timeout
2952 disc_cause
= TERM_PORT_ERROR
;
2953 disc_reason
= "LCP: echo request timeout";
2955 case 13: // auth: fsm timeout
2956 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2957 disc_reason
= "Authentication: FSM timeout";
2959 case 15: // auth: unacceptable auth protocol
2960 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2961 disc_reason
= "Unacceptable authentication protocol";
2963 case 16: // auth: authentication failed
2964 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2965 disc_reason
= "Authentication failed";
2967 case 17: // ncp: fsm timeout
2968 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2969 disc_reason
= "NCP: FSM timeout";
2971 case 18: // ncp: no ncps available
2972 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2973 disc_reason
= "NCP: no NCPs available";
2975 case 19: // ncp: failure to converge on acceptable address
2976 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2977 disc_reason
= (dir
== 1)
2978 ? "NCP: too many Configure-Naks received from peer"
2979 : "NCP: too many Configure-Naks sent to peer";
2981 case 20: // ncp: user not permitted to use any address
2982 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2983 disc_reason
= (dir
== 1)
2984 ? "NCP: local link address not acceptable to peer"
2985 : "NCP: remote link address not acceptable";
2992 static char e
[] = "unknown AVP 0xXXXX";
2993 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2995 result
= 2; // general error
2996 error
= 8; // unknown mandatory AVP
2997 sprintf((msg
= e
) + 14, "%04x", mtype
);
3004 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3008 case 1: // SCCRQ - Start Control Connection Request
3009 tunnel
[t
].state
= TUNNELOPENING
;
3010 LOG(3, s
, t
, "Received SCCRQ\n");
3011 if (main_quit
!= QUIT_SHUTDOWN
)
3013 LOG(3, s
, t
, "sending SCCRP\n");
3014 controlt
*c
= controlnew(2); // sending SCCRP
3015 control16(c
, 2, version
, 1); // protocol version
3016 control32(c
, 3, 3, 1); // framing
3017 controls(c
, 7, hostname
, 1); // host name
3018 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
3019 control16(c
, 9, t
, 1); // assigned tunnel
3020 controladd(c
, 0, t
); // send the resply
3024 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3028 tunnel
[t
].state
= TUNNELOPEN
;
3029 tunnel
[t
].lastrec
= time_now
;
3031 LOG(3, s
, t
, "Received SCCRP\n");
3032 if (main_quit
!= QUIT_SHUTDOWN
)
3034 if (tunnel
[t
].isremotelns
&& chapresponse
)
3038 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3039 // check authenticator
3040 if (memcmp(hash
, chapresponse
, 16) == 0)
3042 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3043 controlt
*c
= controlnew(3); // sending SCCCN
3044 controls(c
, 7, hostname
, 1); // host name
3045 controls(c
, 8, Vendor_name
, 1); // Vendor name
3046 control16(c
, 2, version
, 1); // protocol version
3047 control32(c
, 3, 3, 1); // framing Capabilities
3048 control16(c
, 9, t
, 1); // assigned tunnel
3049 controladd(c
, 0, t
); // send
3053 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3059 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3064 LOG(3, s
, t
, "Received SCCN\n");
3065 tunnel
[t
].state
= TUNNELOPEN
;
3066 tunnel
[t
].lastrec
= time_now
;
3067 controlnull(t
); // ack
3070 LOG(3, s
, t
, "Received StopCCN\n");
3071 controlnull(t
); // ack
3072 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3075 LOG(3, s
, t
, "Received HELLO\n");
3076 controlnull(t
); // simply ACK
3080 LOG(3, s
, t
, "Received OCRQ\n");
3084 LOG(3, s
, t
, "Received OCRO\n");
3088 LOG(3, s
, t
, "Received OCCN\n");
3091 LOG(3, s
, t
, "Received ICRQ\n");
3092 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3094 controlt
*c
= controlnew(11); // ICRP
3096 LOG(3, s
, t
, "Sending ICRP\n");
3099 sessionfree
= session
[s
].next
;
3100 memset(&session
[s
], 0, sizeof(session
[s
]));
3102 if (s
> config
->cluster_highest_sessionid
)
3103 config
->cluster_highest_sessionid
= s
;
3105 session
[s
].opened
= time_now
;
3106 session
[s
].tunnel
= t
;
3107 session
[s
].far
= asession
;
3108 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3109 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3110 control16(c
, 14, s
, 1); // assigned session
3111 controladd(c
, asession
, t
); // send the reply
3113 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3114 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3116 session
[s
].ppp
.phase
= Establish
;
3117 session
[s
].ppp
.lcp
= Starting
;
3119 STAT(session_created
);
3124 controlt
*c
= controlnew(14); // CDN
3125 LOG(3, s
, t
, "Sending CDN\n");
3128 STAT(session_overflow
);
3129 LOG(1, 0, t
, "No free sessions\n");
3130 control16(c
, 1, 4, 0); // temporary lack of resources
3133 control16(c
, 1, 2, 7); // shutting down, try another
3135 controladd(c
, asession
, t
); // send the message
3140 LOG(3, s
, t
, "Received ICRP\n");
3141 if (session
[s
].forwardtosession
)
3143 controlt
*c
= controlnew(12); // ICCN
3145 session
[s
].opened
= time_now
;
3146 session
[s
].tunnel
= t
;
3147 session
[s
].far
= asession
;
3148 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3150 control32(c
, 19, 1, 1); // Framing Type
3151 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3152 controladd(c
, asession
, t
); // send the message
3153 LOG(3, s
, t
, "Sending ICCN\n");
3158 LOG(3, s
, t
, "Received ICCN\n");
3159 if (amagic
== 0) amagic
= time_now
;
3160 session
[s
].magic
= amagic
; // set magic number
3161 session
[s
].flags
= aflags
; // set flags received
3162 session
[s
].mru
= PPPoE_MRU
; // default
3163 controlnull(t
); // ack
3166 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3167 sess_local
[s
].ppp_mru
= MRU
;
3169 // Set multilink options before sending initial LCP packet
3170 sess_local
[s
].mp_mrru
= 1614;
3171 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_address
? config
->iftun_address
: my_address
);
3174 change_state(s
, lcp
, RequestSent
);
3178 LOG(3, s
, t
, "Received CDN\n");
3179 controlnull(t
); // ack
3180 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3183 LOG(1, s
, t
, "Missing message type\n");
3186 STAT(tunnel_rx_errors
);
3188 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3190 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3193 if (chapresponse
) free(chapresponse
);
3194 cluster_send_tunnel(t
);
3198 LOG(4, s
, t
, " Got a ZLB ack\n");
3205 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3206 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3207 { // HDLC address header, discard
3213 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3214 STAT(tunnel_rx_errors
);
3224 proto
= ntohs(*(uint16_t *) p
);
3230 if (session
[s
].forwardtosession
)
3232 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3233 // Forward to LAC/BAS or Remote LNS session
3234 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3237 else if (config
->auth_tunnel_change_addr_src
)
3239 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3240 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3242 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3243 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3244 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3246 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3251 if (s
&& !session
[s
].opened
) // Is something wrong??
3253 if (!config
->cluster_iam_master
)
3255 // Pass it off to the master to deal with..
3256 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3260 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3261 STAT(tunnel_rx_errors
);
3265 if (proto
== PPPPAP
)
3267 session
[s
].last_packet
= time_now
;
3268 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3269 processpap(s
, t
, p
, l
);
3271 else if (proto
== PPPCHAP
)
3273 session
[s
].last_packet
= time_now
;
3274 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3275 processchap(s
, t
, p
, l
);
3277 else if (proto
== PPPLCP
)
3279 session
[s
].last_packet
= time_now
;
3280 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3281 processlcp(s
, t
, p
, l
);
3283 else if (proto
== PPPIPCP
)
3285 session
[s
].last_packet
= time_now
;
3286 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3287 processipcp(s
, t
, p
, l
);
3289 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3291 session
[s
].last_packet
= time_now
;
3292 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3293 processipv6cp(s
, t
, p
, l
);
3295 else if (proto
== PPPCCP
)
3297 session
[s
].last_packet
= time_now
;
3298 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3299 processccp(s
, t
, p
, l
);
3301 else if (proto
== PPPIP
)
3305 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3306 return; // closing session, PPP not processed
3309 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3310 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3312 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3316 processipin(s
, t
, p
, l
);
3318 else if (proto
== PPPMP
)
3322 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3323 return; // closing session, PPP not processed
3326 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3327 if (!config
->cluster_iam_master
)
3329 // The fragments reconstruction is managed by the Master.
3330 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3334 processmpin(s
, t
, p
, l
);
3336 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3340 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3341 return; // closing session, PPP not processed
3344 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3345 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3347 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3351 processipv6in(s
, t
, p
, l
);
3353 else if (session
[s
].ppp
.lcp
== Opened
)
3355 session
[s
].last_packet
= time_now
;
3356 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3357 protoreject(s
, t
, p
, l
, proto
);
3361 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3362 proto
, ppp_state(session
[s
].ppp
.lcp
));
3367 // read and process packet on tun
3368 // (i.e. this routine writes to buf[-8]).
3369 static void processtun(uint8_t * buf
, int len
)
3371 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3372 STAT(tun_rx_packets
);
3373 INC_STAT(tun_rx_bytes
, len
);
3381 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3382 STAT(tun_rx_errors
);
3386 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3387 processipout(buf
, len
);
3388 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3389 && config
->ipv6_prefix
.s6_addr
[0])
3390 processipv6out(buf
, len
);
3395 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3396 // that we look at the whole of the tunnel, radius and session tables
3398 static void regular_cleanups(double period
)
3400 // Next tunnel, radius and session to check for actions on.
3401 static tunnelidt t
= 0;
3403 static sessionidt s
= 0;
3416 // divide up tables into slices based on the last run
3417 t_slice
= config
->cluster_highest_tunnelid
* period
;
3418 r_slice
= (MAXRADIUS
- 1) * period
;
3419 s_slice
= config
->cluster_highest_sessionid
* period
;
3423 else if (t_slice
> config
->cluster_highest_tunnelid
)
3424 t_slice
= config
->cluster_highest_tunnelid
;
3428 else if (r_slice
> (MAXRADIUS
- 1))
3429 r_slice
= MAXRADIUS
- 1;
3433 else if (s_slice
> config
->cluster_highest_sessionid
)
3434 s_slice
= config
->cluster_highest_sessionid
;
3436 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3438 for (i
= 0; i
< t_slice
; i
++)
3441 if (t
> config
->cluster_highest_tunnelid
)
3444 // check for expired tunnels
3445 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3447 STAT(tunnel_timeout
);
3448 tunnelkill(t
, "Expired");
3452 // check for message resend
3453 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3455 // resend pending messages as timeout on reply
3456 if (tunnel
[t
].retry
<= TIME
)
3458 controlt
*c
= tunnel
[t
].controls
;
3459 uint16_t w
= tunnel
[t
].window
;
3460 tunnel
[t
].try++; // another try
3461 if (tunnel
[t
].try > 5)
3462 tunnelkill(t
, "Timeout on control message"); // game over
3466 tunnelsend(c
->buf
, c
->length
, t
);
3474 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3476 controlt
*c
= controlnew(6); // sending HELLO
3477 controladd(c
, 0, t
); // send the message
3478 LOG(3, 0, t
, "Sending HELLO message\n");
3482 // Check for tunnel changes requested from the CLI
3483 if ((a
= cli_tunnel_actions
[t
].action
))
3485 cli_tunnel_actions
[t
].action
= 0;
3486 if (a
& CLI_TUN_KILL
)
3488 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3489 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3495 for (i
= 0; i
< r_slice
; i
++)
3501 if (!radius
[r
].state
)
3504 if (radius
[r
].retry
<= TIME
)
3511 for (i
= 0; i
< s_slice
; i
++)
3514 if (s
> config
->cluster_highest_sessionid
)
3517 if (!session
[s
].opened
) // Session isn't in use
3520 // check for expired sessions
3523 if (session
[s
].die
<= TIME
)
3525 sessionkill(s
, "Expired");
3532 if (sess_local
[s
].lcp
.restart
<= time_now
)
3534 int next_state
= session
[s
].ppp
.lcp
;
3535 switch (session
[s
].ppp
.lcp
)
3539 next_state
= RequestSent
;
3542 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3544 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3545 sendlcp(s
, session
[s
].tunnel
);
3546 change_state(s
, lcp
, next_state
);
3550 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3551 STAT(session_timeout
);
3561 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3563 int next_state
= session
[s
].ppp
.ipcp
;
3564 switch (session
[s
].ppp
.ipcp
)
3568 next_state
= RequestSent
;
3571 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3573 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3574 sendipcp(s
, session
[s
].tunnel
);
3575 change_state(s
, ipcp
, next_state
);
3579 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3580 STAT(session_timeout
);
3590 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3592 int next_state
= session
[s
].ppp
.ipv6cp
;
3593 switch (session
[s
].ppp
.ipv6cp
)
3597 next_state
= RequestSent
;
3600 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3602 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3603 sendipv6cp(s
, session
[s
].tunnel
);
3604 change_state(s
, ipv6cp
, next_state
);
3608 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3609 change_state(s
, ipv6cp
, Stopped
);
3616 if (sess_local
[s
].ccp
.restart
<= time_now
)
3618 int next_state
= session
[s
].ppp
.ccp
;
3619 switch (session
[s
].ppp
.ccp
)
3623 next_state
= RequestSent
;
3626 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3628 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3629 sendccp(s
, session
[s
].tunnel
);
3630 change_state(s
, ccp
, next_state
);
3634 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3635 change_state(s
, ccp
, Stopped
);
3642 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3643 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3645 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3646 STAT(session_timeout
);
3651 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3652 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= config
->echo_timeout
) &&
3653 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3655 uint8_t b
[MAXETHER
];
3657 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3661 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3662 *(uint16_t *)(q
+ 2) = htons(8); // Length
3663 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3665 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3666 (int)(time_now
- session
[s
].last_packet
));
3667 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3668 sess_local
[s
].last_echo
= time_now
;
3672 // Drop sessions who have reached session_timeout seconds
3673 if (session
[s
].session_timeout
)
3675 bundleidt bid
= session
[s
].bundle
;
3678 if (time_now
- bundle
[bid
].last_check
>= 1)
3680 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3681 bundle
[bid
].last_check
= time_now
;
3682 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3685 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3687 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3694 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3696 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3702 // Drop sessions who have reached idle_timeout seconds
3703 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3705 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3706 STAT(session_timeout
);
3711 // Check for actions requested from the CLI
3712 if ((a
= cli_session_actions
[s
].action
))
3716 cli_session_actions
[s
].action
= 0;
3717 if (a
& CLI_SESS_KILL
)
3719 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3720 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3721 a
= 0; // dead, no need to check for other actions
3725 if (a
& CLI_SESS_NOSNOOP
)
3727 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3728 session
[s
].snoop_ip
= 0;
3729 session
[s
].snoop_port
= 0;
3733 else if (a
& CLI_SESS_SNOOP
)
3735 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3736 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3737 cli_session_actions
[s
].snoop_port
);
3739 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3740 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3745 if (a
& CLI_SESS_NOTHROTTLE
)
3747 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3748 throttle_session(s
, 0, 0);
3752 else if (a
& CLI_SESS_THROTTLE
)
3754 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3755 cli_session_actions
[s
].throttle_in
,
3756 cli_session_actions
[s
].throttle_out
);
3758 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3763 if (a
& CLI_SESS_NOFILTER
)
3765 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3766 filter_session(s
, 0, 0);
3770 else if (a
& CLI_SESS_FILTER
)
3772 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3773 cli_session_actions
[s
].filter_in
,
3774 cli_session_actions
[s
].filter_out
);
3776 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3782 cluster_send_session(s
);
3785 // RADIUS interim accounting
3786 if (config
->radius_accounting
&& config
->radius_interim
> 0
3787 && session
[s
].ip
&& !session
[s
].walled_garden
3788 && !sess_local
[s
].radius
// RADIUS already in progress
3789 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3790 && session
[s
].flags
& SESSION_STARTED
)
3792 int rad
= radiusnew(s
);
3795 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3796 STAT(radius_overflow
);
3800 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3801 session
[s
].user
, session
[s
].unique_id
);
3803 radiussend(rad
, RADIUSINTERIM
);
3804 sess_local
[s
].last_interim
= time_now
;
3809 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3810 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3814 // Are we in the middle of a tunnel update, or radius
3817 static int still_busy(void)
3820 static clockt last_talked
= 0;
3821 static clockt start_busy_wait
= 0;
3824 static time_t stopped_bgp
= 0;
3829 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3831 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3832 if (bgp_peers
[i
].state
== Established
)
3833 bgp_stop(&bgp_peers
[i
]);
3835 stopped_bgp
= time_now
;
3837 if (!config
->cluster_iam_master
)
3839 // we don't want to become master
3840 cluster_send_ping(0);
3846 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3851 if (!config
->cluster_iam_master
)
3854 if (main_quit
== QUIT_SHUTDOWN
)
3856 static int dropped
= 0;
3861 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3862 for (i
= 1; i
< MAXTUNNEL
; i
++)
3863 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3864 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3870 if (start_busy_wait
== 0)
3871 start_busy_wait
= TIME
;
3873 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3875 if (!tunnel
[i
].controlc
)
3878 if (last_talked
!= TIME
)
3880 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3886 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3887 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3889 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3893 for (i
= 1; i
< MAXRADIUS
; i
++)
3895 if (radius
[i
].state
== RADIUSNULL
)
3897 if (radius
[i
].state
== RADIUSWAIT
)
3900 if (last_talked
!= TIME
)
3902 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3912 # include <sys/epoll.h>
3914 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3915 # include "fake_epoll.h"
3919 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink, udplac
3922 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3926 // additional polled fds
3928 # define EXTRA_FDS BGP_NUM_PEERS
3930 # define EXTRA_FDS 0
3933 // main loop - gets packets on tun or udp and processes them
3934 static void mainloop(void)
3938 uint8_t *p
= buf
+ 8; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
3939 int size_bufp
= sizeof(buf
) - 8;
3940 clockt next_cluster_ping
= 0; // send initial ping immediately
3941 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3942 int maxevent
= sizeof(events
)/sizeof(*events
);
3944 if ((epollfd
= epoll_create(maxevent
)) < 0)
3946 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3951 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\n",
3952 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
, udplacfd
);
3954 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3955 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3958 /* setup our fds to poll for input */
3960 static struct event_data d
[BASE_FDS
];
3961 struct epoll_event e
;
3968 d
[i
].type
= FD_TYPE_CLI
;
3969 e
.data
.ptr
= &d
[i
++];
3970 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3973 d
[i
].type
= FD_TYPE_CLUSTER
;
3974 e
.data
.ptr
= &d
[i
++];
3975 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3977 d
[i
].type
= FD_TYPE_TUN
;
3978 e
.data
.ptr
= &d
[i
++];
3979 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3981 d
[i
].type
= FD_TYPE_UDP
;
3982 e
.data
.ptr
= &d
[i
++];
3983 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3985 d
[i
].type
= FD_TYPE_CONTROL
;
3986 e
.data
.ptr
= &d
[i
++];
3987 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3989 d
[i
].type
= FD_TYPE_DAE
;
3990 e
.data
.ptr
= &d
[i
++];
3991 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3993 d
[i
].type
= FD_TYPE_NETLINK
;
3994 e
.data
.ptr
= &d
[i
++];
3995 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3998 d
[i
].type
= FD_TYPE_UDPLAC
;
3999 e
.data
.ptr
= &d
[i
++];
4000 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udplacfd
, &e
);
4005 signal(SIGPIPE
, SIG_IGN
);
4006 bgp_setup(config
->as_number
);
4007 if (config
->bind_address
)
4008 bgp_add_route(config
->bind_address
, 0xffffffff);
4010 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4012 if (config
->neighbour
[i
].name
[0])
4013 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4014 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4015 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4016 0); /* 0 = routing disabled */
4020 while (!main_quit
|| still_busy())
4030 config
->reload_config
++;
4033 if (config
->reload_config
)
4035 config
->reload_config
= 0;
4043 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4044 STAT(select_called
);
4049 if (errno
== EINTR
||
4050 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4053 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4059 struct sockaddr_in addr
;
4060 struct in_addr local
;
4065 int udplac_ready
= 0;
4066 int udplac_pkts
= 0;
4069 int cluster_ready
= 0;
4072 int cluster_pkts
= 0;
4074 uint32_t bgp_events
[BGP_NUM_PEERS
];
4075 memset(bgp_events
, 0, sizeof(bgp_events
));
4078 for (c
= n
, i
= 0; i
< c
; i
++)
4080 struct event_data
*d
= events
[i
].data
.ptr
;
4084 case FD_TYPE_CLI
: // CLI connections
4088 alen
= sizeof(addr
);
4089 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4095 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4101 // these are handled below, with multiple interleaved reads
4102 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4103 case FD_TYPE_TUN
: tun_ready
++; break;
4104 case FD_TYPE_UDP
: udp_ready
++; break;
4106 case FD_TYPE_UDPLAC
: udplac_ready
++; break;
4108 case FD_TYPE_CONTROL
: // nsctl commands
4109 alen
= sizeof(addr
);
4110 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4111 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
4115 case FD_TYPE_DAE
: // DAE requests
4116 alen
= sizeof(addr
);
4117 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4118 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
4122 case FD_TYPE_RADIUS
: // RADIUS response
4123 alen
= sizeof(addr
);
4124 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4125 if (s
>= 0 && config
->cluster_iam_master
)
4127 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4128 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4129 processrad(buf
, s
, d
->index
);
4131 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4132 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4140 bgp_events
[d
->index
] = events
[i
].events
;
4145 case FD_TYPE_NETLINK
:
4147 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
4148 s
= netlink_recv(buf
, sizeof(buf
));
4149 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4151 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4154 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4156 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4161 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4166 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
);
4172 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4177 bgp_process(bgp_events
);
4180 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4185 alen
= sizeof(addr
);
4186 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
4188 processudp(buf
, s
, &addr
);
4201 alen
= sizeof(addr
);
4202 if ((s
= recvfrom(udplacfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
4204 if (!config
->disable_lac_func
)
4205 processudp(buf
, s
, &addr
);
4219 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4234 alen
= sizeof(addr
);
4235 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4237 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
4248 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4249 STAT(multi_read_used
);
4251 if (c
>= config
->multi_read_count
)
4254 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d rmlns packets\n",
4255 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
, udplac_pkts
);
4257 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
4258 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
4260 STAT(multi_read_exceeded
);
4266 /* no event received, but timers could still have expired */
4267 bgp_process_peers_timers();
4272 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4274 // Log current traffic stats
4275 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4276 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4277 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4278 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4279 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4281 udp_tx
= udp_rx
= 0;
4282 udp_rx_pkt
= eth_rx_pkt
= 0;
4283 eth_tx
= eth_rx
= 0;
4286 if (config
->dump_speed
)
4287 printf("%s\n", config
->bandwidth
);
4289 // Update the internal time counter
4290 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4294 struct param_timer p
= { time_now
};
4295 run_plugins(PLUGIN_TIMER
, &p
);
4299 // Runs on every machine (master and slaves).
4300 if (next_cluster_ping
<= TIME
)
4302 // Check to see which of the cluster is still alive..
4304 cluster_send_ping(basetime
); // Only does anything if we're a slave
4305 cluster_check_master(); // ditto.
4307 cluster_heartbeat(); // Only does anything if we're a master.
4308 cluster_check_slaves(); // ditto.
4310 master_update_counts(); // If we're a slave, send our byte counters to our master.
4312 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4313 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4315 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4318 if (!config
->cluster_iam_master
)
4321 // Run token bucket filtering queue..
4322 // Only run it every 1/10th of a second.
4324 static clockt last_run
= 0;
4325 if (last_run
!= TIME
)
4332 // Handle timeouts, retries etc.
4334 static double last_clean
= 0;
4338 TIME
= now(&this_clean
);
4339 diff
= this_clean
- last_clean
;
4341 // Run during idle time (after we've handled
4342 // all incoming packets) or every 1/10th sec
4343 if (!more
|| diff
> 0.1)
4345 regular_cleanups(diff
);
4346 last_clean
= this_clean
;
4350 if (*config
->accounting_dir
)
4352 static clockt next_acct
= 0;
4353 static clockt next_shut_acct
= 0;
4355 if (next_acct
<= TIME
)
4357 // Dump accounting data
4358 next_acct
= TIME
+ ACCT_TIME
;
4359 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4362 else if (next_shut_acct
<= TIME
)
4364 // Dump accounting data for shutdown sessions
4365 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4372 // Are we the master and shutting down??
4373 if (config
->cluster_iam_master
)
4374 cluster_heartbeat(); // Flush any queued changes..
4376 // Ok. Notify everyone we're shutting down. If we're
4377 // the master, this will force an election.
4378 cluster_send_ping(0);
4381 // Important!!! We MUST not process any packets past this point!
4382 LOG(1, 0, 0, "Shutdown complete\n");
4385 static void stripdomain(char *host
)
4389 if ((p
= strchr(host
, '.')))
4395 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4401 while (fgets(buf
, sizeof(buf
), resolv
))
4403 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4406 if (!isspace(buf
[6]))
4410 while (isspace(*b
)) b
++;
4415 while (*b
&& !isspace(*b
)) b
++;
4417 if (buf
[0] == 'd') // domain is canonical
4423 // first search line
4426 // hold, may be subsequent domain line
4427 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4438 int hl
= strlen(host
);
4439 int dl
= strlen(domain
);
4440 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4441 host
[hl
-dl
- 1] = 0;
4445 *p
= 0; // everything after first dot
4450 // Init data structures
4451 static void initdata(int optdebug
, char *optconfig
)
4455 if (!(config
= shared_malloc(sizeof(configt
))))
4457 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4461 memset(config
, 0, sizeof(configt
));
4462 time(&config
->start_time
);
4463 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4464 config
->debug
= optdebug
;
4465 config
->num_tbfs
= MAXTBFS
;
4466 config
->rl_rate
= 28; // 28kbps
4467 config
->cluster_mcast_ttl
= 1;
4468 config
->cluster_master_min_adv
= 1;
4469 config
->ppp_restart_time
= 3;
4470 config
->ppp_max_configure
= 10;
4471 config
->ppp_max_failure
= 5;
4472 config
->kill_timedout_sessions
= 1;
4473 strcpy(config
->random_device
, RANDOMDEVICE
);
4474 // Set default value echo_timeout and idle_echo_timeout
4475 config
->echo_timeout
= ECHO_TIMEOUT
;
4476 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4478 log_stream
= stderr
;
4481 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4483 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4486 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4489 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4491 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4494 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4496 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4499 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4501 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4504 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4506 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4509 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4511 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4515 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4517 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4521 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4523 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4527 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4529 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4533 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4535 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4538 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4540 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4542 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4545 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4547 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4549 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4552 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4554 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4555 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4556 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4557 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4558 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4560 // Put all the sessions on the free list marked as undefined.
4561 for (i
= 1; i
< MAXSESSION
; i
++)
4563 session
[i
].next
= i
+ 1;
4564 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4566 session
[MAXSESSION
- 1].next
= 0;
4569 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4570 for (i
= 1; i
< MAXTUNNEL
; i
++)
4571 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4573 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4574 bundle
[i
].state
= BUNDLEUNDEF
;
4579 // Grab my hostname unless it's been specified
4580 gethostname(hostname
, sizeof(hostname
));
4581 stripdomain(hostname
);
4584 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4587 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4589 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4595 lac_initremotelnsdata();
4599 static int assign_ip_address(sessionidt s
)
4603 time_t best_time
= time_now
;
4604 char *u
= session
[s
].user
;
4608 CSTAT(assign_ip_address
);
4610 for (i
= 1; i
< ip_pool_size
; i
++)
4612 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4615 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4622 if (ip_address_pool
[i
].last
< best_time
)
4625 if (!(best_time
= ip_address_pool
[i
].last
))
4626 break; // never used, grab this one
4632 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4636 session
[s
].ip
= ip_address_pool
[best
].address
;
4637 session
[s
].ip_pool_index
= best
;
4638 ip_address_pool
[best
].assigned
= 1;
4639 ip_address_pool
[best
].last
= time_now
;
4640 ip_address_pool
[best
].session
= s
;
4641 if (session
[s
].walled_garden
)
4642 /* Don't track addresses of users in walled garden (note: this
4643 means that their address isn't "sticky" even if they get
4645 ip_address_pool
[best
].user
[0] = 0;
4647 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4650 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4651 reuse
? "Reusing" : "Allocating", best
);
4656 static void free_ip_address(sessionidt s
)
4658 int i
= session
[s
].ip_pool_index
;
4661 CSTAT(free_ip_address
);
4664 return; // what the?
4666 if (i
< 0) // Is this actually part of the ip pool?
4670 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4672 ip_address_pool
[i
].assigned
= 0;
4673 ip_address_pool
[i
].session
= 0;
4674 ip_address_pool
[i
].last
= time_now
;
4678 // Fsck the address pool against the session table.
4679 // Normally only called when we become a master.
4681 // This isn't perfect: We aren't keep tracking of which
4682 // users used to have an IP address.
4684 void rebuild_address_pool(void)
4689 // Zero the IP pool allocation, and build
4690 // a map from IP address to pool index.
4691 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4693 ip_address_pool
[i
].assigned
= 0;
4694 ip_address_pool
[i
].session
= 0;
4695 if (!ip_address_pool
[i
].address
)
4698 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4701 for (i
= 0; i
< MAXSESSION
; ++i
)
4704 if (!(session
[i
].opened
&& session
[i
].ip
))
4707 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4709 if (session
[i
].ip_pool_index
< 0)
4711 // Not allocated out of the pool.
4712 if (ipid
< 1) // Not found in the pool either? good.
4715 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4716 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4718 // Fall through and process it as part of the pool.
4722 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4724 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4726 session
[i
].ip_pool_index
= ipid
;
4730 ip_address_pool
[ipid
].assigned
= 1;
4731 ip_address_pool
[ipid
].session
= i
;
4732 ip_address_pool
[ipid
].last
= time_now
;
4733 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4734 session
[i
].ip_pool_index
= ipid
;
4735 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4740 // Fix the address pool to match a changed session.
4741 // (usually when the master sends us an update).
4742 static void fix_address_pool(int sid
)
4746 ipid
= session
[sid
].ip_pool_index
;
4748 if (ipid
> ip_pool_size
)
4749 return; // Ignore it. rebuild_address_pool will fix it up.
4751 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4752 return; // Just ignore it. rebuild_address_pool will take care of it.
4754 ip_address_pool
[ipid
].assigned
= 1;
4755 ip_address_pool
[ipid
].session
= sid
;
4756 ip_address_pool
[ipid
].last
= time_now
;
4757 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4761 // Add a block of addresses to the IP pool to hand out.
4763 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4767 prefixlen
= 32; // Host route only.
4769 addr
&= 0xffffffff << (32 - prefixlen
);
4771 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4774 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4776 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4777 continue; // Skip 0 and broadcast addresses.
4779 ip_address_pool
[ip_pool_size
].address
= i
;
4780 ip_address_pool
[ip_pool_size
].assigned
= 0;
4782 if (ip_pool_size
>= MAXIPPOOL
)
4784 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4790 // Initialize the IP address pool
4791 static void initippool()
4796 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4798 if (!(f
= fopen(IPPOOLFILE
, "r")))
4800 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4804 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4807 buf
[4095] = 0; // Force it to be zero terminated/
4809 if (*buf
== '#' || *buf
== '\n')
4810 continue; // Skip comments / blank lines
4811 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4812 if ((p
= (char *)strchr(buf
, ':')))
4816 src
= inet_addr(buf
);
4817 if (src
== INADDR_NONE
)
4819 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4822 // This entry is for a specific IP only
4823 if (src
!= config
->bind_address
)
4828 if ((p
= (char *)strchr(pool
, '/')))
4832 in_addr_t start
= 0;
4834 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4836 if (!*p
|| !(numbits
= atoi(p
)))
4838 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4841 start
= ntohl(inet_addr(pool
));
4843 // Add a static route for this pool
4844 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4845 fmtaddr(htonl(start
), 0), numbits
);
4847 routeset(0, start
, numbits
, 0, 1);
4849 add_to_ip_pool(start
, numbits
);
4853 // It's a single ip address
4854 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4858 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4861 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4863 struct sockaddr_in snoop_addr
= {0};
4864 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4867 snoop_addr
.sin_family
= AF_INET
;
4868 snoop_addr
.sin_addr
.s_addr
= destination
;
4869 snoop_addr
.sin_port
= ntohs(port
);
4871 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4872 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4873 htons(snoop_addr
.sin_port
));
4875 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4876 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4878 STAT(packets_snooped
);
4881 static int dump_session(FILE **f
, sessiont
*s
)
4884 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4886 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4892 char filename
[1024];
4894 time_t now
= time(NULL
);
4896 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4897 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4899 if (!(*f
= fopen(filename
, "w")))
4901 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4905 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4906 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4911 "# format: username ip qos uptxoctets downrxoctets\n",
4913 fmtaddr(config
->iftun_address
? config
->iftun_address
: my_address
, 0),
4918 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4919 fprintf(*f
, "%s %s %d %u %u\n",
4920 s
->user
, // username
4921 fmtaddr(htonl(s
->ip
), 0), // ip
4922 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4923 (uint32_t) s
->cin_delta
, // uptxoctets
4924 (uint32_t) s
->cout_delta
); // downrxoctets
4926 s
->cin_delta
= s
->cout_delta
= 0;
4931 static void dump_acct_info(int all
)
4937 CSTAT(dump_acct_info
);
4941 for (i
= 0; i
< shut_acct_n
; i
++)
4942 dump_session(&f
, &shut_acct
[i
]);
4948 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4949 dump_session(&f
, &session
[i
]);
4956 int main(int argc
, char *argv
[])
4960 char *optconfig
= CONFIGFILE
;
4962 time(&basetime
); // start clock
4965 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4970 if (fork()) exit(0);
4972 freopen("/dev/null", "r", stdin
);
4973 freopen("/dev/null", "w", stdout
);
4974 freopen("/dev/null", "w", stderr
);
4983 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4986 printf("Args are:\n"
4987 "\t-d\t\tDetach from terminal\n"
4988 "\t-c <file>\tConfig file\n"
4989 "\t-h <hostname>\tForce hostname\n"
4997 // Start the timer routine off
4999 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5002 initdata(optdebug
, optconfig
);
5006 /* set hostname /after/ having read the config file */
5007 if (*config
->hostname
)
5008 strcpy(hostname
, config
->hostname
);
5009 cli_init_complete(hostname
);
5011 init_tbf(config
->num_tbfs
);
5013 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5014 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5015 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5018 rlim
.rlim_cur
= RLIM_INFINITY
;
5019 rlim
.rlim_max
= RLIM_INFINITY
;
5020 // Remove the maximum core size
5021 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5022 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5024 // Make core dumps go to /tmp
5028 if (config
->scheduler_fifo
)
5031 struct sched_param params
= {0};
5032 params
.sched_priority
= 1;
5034 if (get_nprocs() < 2)
5036 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5037 config
->scheduler_fifo
= 0;
5041 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5043 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5047 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5048 config
->scheduler_fifo
= 0;
5055 /* Set up the cluster communications port. */
5056 if (cluster_init() < 0)
5060 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5068 unsigned seed
= time_now
^ getpid();
5069 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5073 signal(SIGHUP
, sighup_handler
);
5074 signal(SIGCHLD
, sigchild_handler
);
5075 signal(SIGTERM
, shutdown_handler
);
5076 signal(SIGINT
, shutdown_handler
);
5077 signal(SIGQUIT
, shutdown_handler
);
5079 // Prevent us from getting paged out
5080 if (config
->lock_pages
)
5082 if (!mlockall(MCL_CURRENT
))
5083 LOG(1, 0, 0, "Locking pages into memory\n");
5085 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5090 /* remove plugins (so cleanup code gets run) */
5093 // Remove the PID file if we wrote it
5094 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5095 unlink(config
->pid_file
);
5097 /* kill CLI children */
5098 signal(SIGTERM
, SIG_IGN
);
5103 static void sighup_handler(int sig
)
5108 static void shutdown_handler(int sig
)
5110 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5113 static void sigchild_handler(int sig
)
5115 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5119 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5122 *challenge_response
= NULL
;
5124 if (!*config
->l2tp_secret
)
5126 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5130 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5132 *challenge_response
= calloc(17, 1);
5135 MD5_Update(&ctx
, &id
, 1);
5136 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5137 MD5_Update(&ctx
, challenge
, challenge_length
);
5138 MD5_Final(*challenge_response
, &ctx
);
5143 static int facility_value(char *name
)
5146 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5148 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5149 return facilitynames
[i
].c_val
;
5154 static void update_config()
5158 static int timeout
= 0;
5159 static int interval
= 0;
5166 if (log_stream
!= stderr
)
5172 if (*config
->log_filename
)
5174 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5176 char *p
= config
->log_filename
+ 7;
5179 openlog("l2tpns", LOG_PID
, facility_value(p
));
5183 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5185 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5187 fseek(log_stream
, 0, SEEK_END
);
5188 setbuf(log_stream
, NULL
);
5192 log_stream
= stderr
;
5193 setbuf(log_stream
, NULL
);
5199 log_stream
= stderr
;
5200 setbuf(log_stream
, NULL
);
5203 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5204 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5206 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5207 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5208 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5210 // reset MRU/MSS globals
5211 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5212 if (MRU
> PPPoE_MRU
)
5215 MSS
= MRU
- TCP_HDRS
;
5218 config
->numradiusservers
= 0;
5219 for (i
= 0; i
< MAXRADSERVER
; i
++)
5220 if (config
->radiusserver
[i
])
5222 config
->numradiusservers
++;
5223 // Set radius port: if not set, take the port from the
5224 // first radius server. For the first radius server,
5225 // take the #defined default value from l2tpns.h
5227 // test twice, In case someone works with
5228 // a secondary radius server without defining
5229 // a primary one, this will work even then.
5230 if (i
> 0 && !config
->radiusport
[i
])
5231 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5232 if (!config
->radiusport
[i
])
5233 config
->radiusport
[i
] = RADPORT
;
5236 if (!config
->numradiusservers
)
5237 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5239 // parse radius_authtypes_s
5240 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5241 p
= config
->radius_authtypes_s
;
5244 char *s
= strpbrk(p
, " \t,");
5250 while (*s
== ' ' || *s
== '\t')
5257 if (!strncasecmp("chap", p
, strlen(p
)))
5259 else if (!strncasecmp("pap", p
, strlen(p
)))
5262 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5264 config
->radius_authtypes
|= type
;
5265 if (!config
->radius_authprefer
)
5266 config
->radius_authprefer
= type
;
5271 if (!config
->radius_authtypes
)
5273 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5274 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5277 // normalise radius_authtypes_s
5278 if (config
->radius_authprefer
== AUTHPAP
)
5280 strcpy(config
->radius_authtypes_s
, "pap");
5281 if (config
->radius_authtypes
& AUTHCHAP
)
5282 strcat(config
->radius_authtypes_s
, ", chap");
5286 strcpy(config
->radius_authtypes_s
, "chap");
5287 if (config
->radius_authtypes
& AUTHPAP
)
5288 strcat(config
->radius_authtypes_s
, ", pap");
5291 if (!config
->radius_dae_port
)
5292 config
->radius_dae_port
= DAEPORT
;
5295 if(!config
->bind_portremotelns
)
5296 config
->bind_portremotelns
= L2TPLACPORT
;
5297 if(!config
->bind_address_remotelns
)
5298 config
->bind_address_remotelns
= INADDR_ANY
;
5300 if(!config
->iftun_address
)
5301 config
->iftun_address
= config
->bind_address
;
5303 // re-initialise the random number source
5304 initrandom(config
->random_device
);
5307 for (i
= 0; i
< MAXPLUGINS
; i
++)
5309 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5312 if (*config
->plugins
[i
])
5315 add_plugin(config
->plugins
[i
]);
5317 else if (*config
->old_plugins
[i
])
5320 remove_plugin(config
->old_plugins
[i
]);
5325 guest_accounts_num
= 0;
5326 char *p2
= config
->guest_user
;
5329 char *s
= strpbrk(p2
, " \t,");
5333 while (*s
== ' ' || *s
== '\t')
5340 strcpy(guest_users
[guest_accounts_num
], p2
);
5341 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5342 guest_accounts_num
++;
5345 // Rebuild the guest_user array
5346 strcpy(config
->guest_user
, "");
5348 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5350 strcat(config
->guest_user
, guest_users
[ui
]);
5351 if (ui
<guest_accounts_num
-1)
5353 strcat(config
->guest_user
, ",");
5358 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5359 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5360 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5361 if (!*config
->cluster_interface
)
5362 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5364 if (!config
->cluster_hb_interval
)
5365 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5367 if (!config
->cluster_hb_timeout
)
5368 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5370 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5372 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5373 // late, ensure we're sufficiently larger than that
5374 int t
= 4 * config
->cluster_hb_interval
+ 11;
5376 if (config
->cluster_hb_timeout
< t
)
5378 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5379 config
->cluster_hb_timeout
= t
;
5382 // Push timing changes to the slaves immediately if we're the master
5383 if (config
->cluster_iam_master
)
5384 cluster_heartbeat();
5386 interval
= config
->cluster_hb_interval
;
5387 timeout
= config
->cluster_hb_timeout
;
5391 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5394 if ((f
= fopen(config
->pid_file
, "w")))
5396 fprintf(f
, "%d\n", getpid());
5398 config
->wrote_pid
= 1;
5402 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5407 static void read_config_file()
5411 if (!config
->config_file
) return;
5412 if (!(f
= fopen(config
->config_file
, "r")))
5414 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5418 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5420 LOG(3, 0, 0, "Done reading config file\n");
5424 int sessionsetup(sessionidt s
, tunnelidt t
)
5426 // A session now exists, set it up
5432 CSTAT(sessionsetup
);
5434 LOG(3, s
, t
, "Doing session setup for session\n");
5436 // Join a bundle if the MRRU option is accepted
5437 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5439 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5440 if (join_bundle(s
) > 0)
5441 cluster_send_bundle(session
[s
].bundle
);
5444 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5445 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5452 assign_ip_address(s
);
5455 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5456 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5459 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5460 fmtaddr(htonl(session
[s
].ip
), 0));
5463 // Make sure this is right
5464 session
[s
].tunnel
= t
;
5466 // zap old sessions with same IP and/or username
5467 // Don't kill gardened sessions - doing so leads to a DoS
5468 // from someone who doesn't need to know the password
5471 user
= session
[s
].user
;
5472 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5474 if (i
== s
) continue;
5475 if (!session
[s
].opened
) break;
5476 // Allow duplicate sessions for multilink ones of the same bundle.
5477 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5479 if (ip
== session
[i
].ip
)
5481 sessionkill(i
, "Duplicate IP address");
5482 cluster_listinvert_session(s
, i
);
5486 if (config
->allow_duplicate_users
) continue;
5487 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5491 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5493 if (!strcasecmp(user
, guest_users
[gu
]))
5499 if (found
) continue;
5501 // Drop the new session in case of duplicate sessionss, not the old one.
5502 if (!strcasecmp(user
, session
[i
].user
))
5503 sessionkill(i
, "Duplicate session for users");
5507 // no need to set a route for the same IP address of the bundle
5508 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5512 // Add the route for this session.
5513 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5515 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5516 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5519 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5522 // Static IPs need to be routed if not already
5523 // convered by a Framed-Route. Anything else is part
5524 // of the IP address pool and is already routed, it
5525 // just needs to be added to the IP cache.
5526 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5527 if (session
[s
].ip_pool_index
== -1) // static ip
5529 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5532 cache_ipmap(session
[s
].ip
, s
);
5535 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5536 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5538 // Run the plugin's against this new session.
5540 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5541 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5544 // Allocate TBFs if throttled
5545 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5546 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5548 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5550 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5551 fmtaddr(htonl(session
[s
].ip
), 0),
5552 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5554 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5556 return 1; // RADIUS OK and IP allocated, done...
5560 // This session just got dropped on us by the master or something.
5561 // Make sure our tables up up to date...
5563 int load_session(sessionidt s
, sessiont
*new)
5569 if (new->ip_pool_index
>= MAXIPPOOL
||
5570 new->tunnel
>= MAXTUNNEL
)
5572 LOG(0, s
, 0, "Strange session update received!\n");
5573 // FIXME! What to do here?
5578 // Ok. All sanity checks passed. Now we're committed to
5579 // loading the new session.
5582 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5584 // See if routes/ip cache need updating
5585 if (new->ip
!= session
[s
].ip
)
5588 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5589 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5590 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5598 // remove old routes...
5599 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5601 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5602 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5605 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5611 if (session
[s
].ip_pool_index
== -1) // static IP
5613 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5615 else // It's part of the IP pool, remove it manually.
5616 uncache_ipmap(session
[s
].ip
);
5621 // add new routes...
5622 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5624 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5625 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5628 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5634 // If there's a new one, add it.
5635 if (new->ip_pool_index
== -1)
5637 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5640 cache_ipmap(new->ip
, s
);
5645 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5646 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5649 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5651 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5655 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5657 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5658 new->filter_out
= 0;
5661 if (new->filter_in
!= session
[s
].filter_in
)
5663 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5664 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5667 if (new->filter_out
!= session
[s
].filter_out
)
5669 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5670 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5673 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5674 // for walking the sessions to forward byte counts to the master.
5675 config
->cluster_highest_sessionid
= s
;
5677 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5679 // Do fixups into address pool.
5680 if (new->ip_pool_index
!= -1)
5681 fix_address_pool(s
);
5686 static void initplugins()
5690 loaded_plugins
= ll_init();
5691 // Initialize the plugins to nothing
5692 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5693 plugins
[i
] = ll_init();
5696 static void *open_plugin(char *plugin_name
, int load
)
5698 char path
[256] = "";
5700 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5701 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5702 return dlopen(path
, RTLD_NOW
);
5705 // plugin callback to get a config value
5706 static void *getconfig(char *key
, enum config_typet type
)
5710 for (i
= 0; config_values
[i
].key
; i
++)
5712 if (!strcmp(config_values
[i
].key
, key
))
5714 if (config_values
[i
].type
== type
)
5715 return ((void *) config
) + config_values
[i
].offset
;
5717 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5718 key
, type
, config_values
[i
].type
);
5724 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5728 static int add_plugin(char *plugin_name
)
5730 static struct pluginfuncs funcs
= {
5735 sessiontbysessionidt
,
5736 sessionidtbysessiont
,
5743 cluster_send_session
,
5746 void *p
= open_plugin(plugin_name
, 1);
5747 int (*initfunc
)(struct pluginfuncs
*);
5752 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5756 if (ll_contains(loaded_plugins
, p
))
5759 return 0; // already loaded
5763 int *v
= dlsym(p
, "plugin_api_version");
5764 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5766 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5772 if ((initfunc
= dlsym(p
, "plugin_init")))
5774 if (!initfunc(&funcs
))
5776 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5782 ll_push(loaded_plugins
, p
);
5784 for (i
= 0; i
< max_plugin_functions
; i
++)
5787 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5789 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5790 ll_push(plugins
[i
], x
);
5794 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5798 static void run_plugin_done(void *plugin
)
5800 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5806 static int remove_plugin(char *plugin_name
)
5808 void *p
= open_plugin(plugin_name
, 0);
5814 if (ll_contains(loaded_plugins
, p
))
5817 for (i
= 0; i
< max_plugin_functions
; i
++)
5820 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5821 ll_delete(plugins
[i
], x
);
5824 ll_delete(loaded_plugins
, p
);
5830 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5834 int run_plugins(int plugin_type
, void *data
)
5836 int (*func
)(void *data
);
5838 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5839 return PLUGIN_RET_ERROR
;
5841 ll_reset(plugins
[plugin_type
]);
5842 while ((func
= ll_next(plugins
[plugin_type
])))
5846 if (r
!= PLUGIN_RET_OK
)
5847 return r
; // stop here
5850 return PLUGIN_RET_OK
;
5853 static void plugins_done()
5857 ll_reset(loaded_plugins
);
5858 while ((p
= ll_next(loaded_plugins
)))
5862 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5864 struct nsctl request
;
5865 struct nsctl response
;
5866 int type
= unpack_control(&request
, buf
, len
);
5870 if (log_stream
&& config
->debug
>= 4)
5874 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5875 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5879 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5880 dump_control(&request
, log_stream
);
5886 case NSCTL_REQ_LOAD
:
5887 if (request
.argc
!= 1)
5889 response
.type
= NSCTL_RES_ERR
;
5891 response
.argv
[0] = "name of plugin required";
5893 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5895 response
.type
= NSCTL_RES_ERR
;
5897 response
.argv
[0] = !r
5898 ? "plugin already loaded"
5899 : "error loading plugin";
5903 response
.type
= NSCTL_RES_OK
;
5909 case NSCTL_REQ_UNLOAD
:
5910 if (request
.argc
!= 1)
5912 response
.type
= NSCTL_RES_ERR
;
5914 response
.argv
[0] = "name of plugin required";
5916 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5918 response
.type
= NSCTL_RES_ERR
;
5920 response
.argv
[0] = !r
5921 ? "plugin not loaded"
5922 : "plugin not found";
5926 response
.type
= NSCTL_RES_OK
;
5932 case NSCTL_REQ_HELP
:
5933 response
.type
= NSCTL_RES_OK
;
5936 ll_reset(loaded_plugins
);
5937 while ((p
= ll_next(loaded_plugins
)))
5939 char **help
= dlsym(p
, "plugin_control_help");
5940 while (response
.argc
< 0xff && help
&& *help
)
5941 response
.argv
[response
.argc
++] = *help
++;
5946 case NSCTL_REQ_CONTROL
:
5948 struct param_control param
= {
5949 config
->cluster_iam_master
,
5956 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5958 if (r
== PLUGIN_RET_ERROR
)
5960 response
.type
= NSCTL_RES_ERR
;
5962 response
.argv
[0] = param
.additional
5964 : "error returned by plugin";
5966 else if (r
== PLUGIN_RET_NOTMASTER
)
5968 static char msg
[] = "must be run on master: 000.000.000.000";
5970 response
.type
= NSCTL_RES_ERR
;
5972 if (config
->cluster_master_address
)
5974 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5975 response
.argv
[0] = msg
;
5979 response
.argv
[0] = "must be run on master: none elected";
5982 else if (!(param
.response
& NSCTL_RESPONSE
))
5984 response
.type
= NSCTL_RES_ERR
;
5986 response
.argv
[0] = param
.response
5987 ? "unrecognised response value from plugin"
5988 : "unhandled action";
5992 response
.type
= param
.response
;
5994 if (param
.additional
)
5997 response
.argv
[0] = param
.additional
;
6005 response
.type
= NSCTL_RES_ERR
;
6007 response
.argv
[0] = "error unpacking control packet";
6010 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6013 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6017 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6020 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6021 if (log_stream
&& config
->debug
>= 4)
6023 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6024 dump_control(&response
, log_stream
);
6028 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6029 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6034 static tunnelidt
new_tunnel()
6037 for (i
= 1; i
< MAXTUNNEL
; i
++)
6039 if (tunnel
[i
].state
== TUNNELFREE
)
6041 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6042 if (i
> config
->cluster_highest_tunnelid
)
6043 config
->cluster_highest_tunnelid
= i
;
6047 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6052 // We're becoming the master. Do any required setup..
6054 // This is principally telling all the plugins that we're
6055 // now a master, and telling them about all the sessions
6056 // that are active too..
6058 void become_master(void)
6061 static struct event_data d
[RADIUS_FDS
];
6062 struct epoll_event e
;
6064 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6066 // running a bunch of iptables commands is slow and can cause
6067 // the master to drop tunnels on takeover--kludge around the
6068 // problem by forking for the moment (note: race)
6069 if (!fork_and_close())
6071 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6073 if (!session
[s
].opened
) // Not an in-use session.
6076 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6083 for (i
= 0; i
< RADIUS_FDS
; i
++)
6085 d
[i
].type
= FD_TYPE_RADIUS
;
6089 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6093 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6099 if (CLI_HELP_REQUESTED
)
6100 return CLI_HELP_NO_ARGS
;
6103 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6105 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6108 if (!session
[s
].opened
)
6111 idle
= time_now
- session
[s
].last_data
;
6112 idle
/= 5 ; // In multiples of 5 seconds.
6122 for (i
= 0; i
< 63; ++i
)
6124 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6126 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6127 cli_print(cli
, "%d total sessions open.", count
);
6131 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6137 if (CLI_HELP_REQUESTED
)
6138 return CLI_HELP_NO_ARGS
;
6141 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6143 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6146 if (!session
[s
].opened
)
6149 d
= time_now
- session
[s
].opened
;
6152 while (d
> 1 && open
< 32)
6162 for (i
= 0; i
< 30; ++i
)
6164 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6167 cli_print(cli
, "%d total sessions open.", count
);
6173 * This unencodes the AVP using the L2TP secret and the previously
6174 * stored random vector. It overwrites the hidden data with the
6175 * unhidden AVP subformat.
6177 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6183 uint16_t m
= htons(type
);
6185 // Compute initial pad
6187 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6188 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6189 MD5_Update(&ctx
, vector
, vec_len
);
6190 MD5_Final(digest
, &ctx
);
6192 // pointer to last decoded 16 octets
6197 // calculate a new pad based on the last decoded block
6198 if (d
>= sizeof(digest
))
6201 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6202 MD5_Update(&ctx
, last
, sizeof(digest
));
6203 MD5_Final(digest
, &ctx
);
6209 *value
++ ^= digest
[d
++];
6214 int find_filter(char const *name
, size_t len
)
6219 for (i
= 0; i
< MAXFILTER
; i
++)
6221 if (!*ip_filters
[i
].name
)
6229 if (strlen(ip_filters
[i
].name
) != len
)
6232 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6239 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6243 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6244 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6245 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6246 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6247 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6253 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6257 case FILTER_FLAG_OP_ANY
:
6258 return (flags
& sflags
) || (~flags
& cflags
);
6260 case FILTER_FLAG_OP_ALL
:
6261 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6263 case FILTER_FLAG_OP_EST
:
6264 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6270 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6272 uint16_t frag_offset
;
6276 uint16_t src_port
= 0;
6277 uint16_t dst_port
= 0;
6279 ip_filter_rulet
*rule
;
6281 if (len
< 20) // up to end of destination address
6284 if ((*buf
>> 4) != 4) // IPv4
6287 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6289 src_ip
= *(in_addr_t
*) (buf
+ 12);
6290 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6292 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6294 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6295 if (len
< l
+ 4) // ports
6298 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6299 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6300 if (proto
== IPPROTO_TCP
)
6302 if (len
< l
+ 14) // flags
6305 flags
= buf
[l
+ 13] & 0x3f;
6309 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6311 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6314 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6315 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6318 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6319 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6324 // layer 4 deny rules are skipped
6325 if (rule
->action
== FILTER_ACTION_DENY
&&
6326 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6334 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6336 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6339 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6342 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6343 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6350 return rule
->action
== FILTER_ACTION_PERMIT
;
6359 tunnelidt
lac_new_tunnel()
6361 return new_tunnel();
6364 void lac_tunnelclear(tunnelidt t
)
6369 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6371 uint16_t version
= 0x0100; // protocol version
6373 tunnel
[t
].state
= TUNNELOPENING
;
6375 // Sent SCCRQ - Start Control Connection Request
6376 controlt
*c
= controlnew(1); // sending SCCRQ
6377 controls(c
, 7, hostname
, 1); // host name
6378 controls(c
, 8, Vendor_name
, 1); // Vendor name
6379 control16(c
, 2, version
, 1); // protocol version
6380 control32(c
, 3, 3, 1); // framing Capabilities
6381 control16(c
, 9, t
, 1); // assigned tunnel
6382 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6383 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6384 controladd(c
, 0, t
); // send
6387 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6389 // Sent ICRQ Incoming-call-request
6390 controlt
*c
= controlnew(10); // ICRQ
6392 control16(c
, 14, s
, 1); // assigned sesion
6393 call_serial_number
++;
6394 control32(c
, 15, call_serial_number
, 1); // call serial number
6395 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6396 controladd(c
, 0, t
); // send
6399 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6401 tunnelshutdown(t
, reason
, result
, error
, msg
);