3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
7 char const *cvs_id_l2tpns
= "$Id: l2tpns.c,v 1.176 2011/01/20 12:48:40 bodea Exp $";
13 #include <linux/if_tun.h>
18 #include <net/route.h>
21 #include <netinet/in.h>
22 #include <netinet/ip6.h>
28 #include <sys/ioctl.h>
29 #include <sys/socket.h>
32 #include <sys/resource.h>
40 #include <sys/sysinfo.h>
42 #include <linux/netlink.h>
43 #include <linux/rtnetlink.h>
50 #include "constants.h"
60 configt
*config
= NULL
; // all configuration
61 int nlfd
= -1; // netlink socket
62 int tunfd
= -1; // tun interface file handle. (network device)
63 int udpfd
= -1; // UDP file handle
64 int controlfd
= -1; // Control signal handle
65 int clifd
= -1; // Socket listening for CLI connections.
66 int daefd
= -1; // Socket listening for DAE connections.
67 int snoopfd
= -1; // UDP file handle for sending out intercept data
68 int *radfds
= NULL
; // RADIUS requests file handles
69 int rand_fd
= -1; // Random data source
70 int cluster_sockfd
= -1; // Intra-cluster communications socket.
71 int epollfd
= -1; // event polling
72 time_t basetime
= 0; // base clock
73 char hostname
[1000] = ""; // us.
74 static int tunidx
; // ifr_ifindex of tun device
75 int nlseqnum
= 0; // netlink sequence number
76 static int syslog_log
= 0; // are we logging to syslog
77 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
78 uint32_t last_id
= 0; // Unique ID for radius accounting
80 char guest_users
[10][32]; // Array of guest users
81 int guest_accounts_num
= 0; // Number of guest users
83 // calculated from config->l2tp_mtu
84 uint16_t MRU
= 0; // PPP MRU
85 uint16_t MSS
= 0; // TCP MSS
87 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
88 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
93 } ip_hash
[256]; // Mapping from IP address to session structures.
97 struct ipv6radix
*branch
;
98 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
101 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
102 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
105 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
106 time_t time_now
= 0; // Current time in seconds since epoch.
107 static char time_now_string
[64] = {0}; // Current time as a string.
108 static int time_changed
= 0; // time_now changed
109 char main_quit
= 0; // True if we're in the process of exiting.
110 static char main_reload
= 0; // Re-load pending
111 linked_list
*loaded_plugins
;
112 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
114 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
115 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
117 config_descriptt config_values
[] = {
118 CONFIG("debug", debug
, INT
),
119 CONFIG("log_file", log_filename
, STRING
),
120 CONFIG("pid_file", pid_file
, STRING
),
121 CONFIG("random_device", random_device
, STRING
),
122 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
123 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
124 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
125 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
126 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
127 CONFIG("primary_dns", default_dns1
, IPv4
),
128 CONFIG("secondary_dns", default_dns2
, IPv4
),
129 CONFIG("primary_radius", radiusserver
[0], IPv4
),
130 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
131 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
132 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
133 CONFIG("radius_accounting", radius_accounting
, BOOL
),
134 CONFIG("radius_interim", radius_interim
, INT
),
135 CONFIG("radius_secret", radiussecret
, STRING
),
136 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
137 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
138 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
139 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
140 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
141 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
142 CONFIG("guest_account", guest_user
, STRING
),
143 CONFIG("bind_address", bind_address
, IPv4
),
144 CONFIG("peer_address", peer_address
, IPv4
),
145 CONFIG("send_garp", send_garp
, BOOL
),
146 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
147 CONFIG("throttle_buckets", num_tbfs
, INT
),
148 CONFIG("accounting_dir", accounting_dir
, STRING
),
149 CONFIG("dump_speed", dump_speed
, BOOL
),
150 CONFIG("multi_read_count", multi_read_count
, INT
),
151 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
152 CONFIG("lock_pages", lock_pages
, BOOL
),
153 CONFIG("icmp_rate", icmp_rate
, INT
),
154 CONFIG("packet_limit", max_packets
, INT
),
155 CONFIG("cluster_address", cluster_address
, IPv4
),
156 CONFIG("cluster_interface", cluster_interface
, STRING
),
157 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
158 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
159 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
160 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
161 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
165 static char *plugin_functions
[] = {
172 "plugin_new_session",
173 "plugin_kill_session",
175 "plugin_radius_response",
176 "plugin_radius_reset",
177 "plugin_radius_account",
178 "plugin_become_master",
179 "plugin_new_session_master",
182 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
184 // Counters for shutdown sessions
185 static sessiont shut_acct
[8192];
186 static sessionidt shut_acct_n
= 0;
188 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
189 bundlet
*bundle
= NULL
; // Array of bundle structures.
190 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
191 sessiont
*session
= NULL
; // Array of session structures.
192 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
193 radiust
*radius
= NULL
; // Array of radius structures.
194 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
195 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
196 static controlt
*controlfree
= 0;
197 struct Tstats
*_statistics
= NULL
;
199 struct Tringbuffer
*ringbuffer
= NULL
;
202 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
203 static void uncache_ipmap(in_addr_t ip
);
204 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
205 static void free_ip_address(sessionidt s
);
206 static void dump_acct_info(int all
);
207 static void sighup_handler(int sig
);
208 static void shutdown_handler(int sig
);
209 static void sigchild_handler(int sig
);
210 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
211 static void update_config(void);
212 static void read_config_file(void);
213 static void initplugins(void);
214 static int add_plugin(char *plugin_name
);
215 static int remove_plugin(char *plugin_name
);
216 static void plugins_done(void);
217 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
218 static tunnelidt
new_tunnel(void);
219 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
220 static void bundleclear(bundleidt b
);
222 // on slaves, alow BGP to withdraw cleanly before exiting
225 // quit actions (master)
226 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
227 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
229 // return internal time (10ths since process startup), set f if given
230 // as a side-effect sets time_now, and time_changed
231 static clockt
now(double *f
)
235 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
236 if (t
.tv_sec
!= time_now
)
241 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
244 // work out a retry time based on try number
245 // This is a straight bounded exponential backoff.
246 // Maximum re-try time is 32 seconds. (2^5).
247 clockt
backoff(uint8_t try)
249 if (try > 5) try = 5; // max backoff
250 return now(NULL
) + 10 * (1 << try);
255 // Log a debug message. Typically called via the LOG macro
257 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
259 static char message
[65536] = {0};
265 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
266 ringbuffer
->tail
= 0;
267 if (ringbuffer
->tail
== ringbuffer
->head
)
268 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
269 ringbuffer
->head
= 0;
271 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
272 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
273 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
274 va_start(ap
, format
);
275 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
280 if (config
->debug
< level
) return;
282 va_start(ap
, format
);
283 vsnprintf(message
, sizeof(message
), format
, ap
);
286 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
288 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
293 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
296 const uint8_t *d
= data
;
298 if (config
->debug
< level
) return;
300 // No support for _log_hex to syslog
303 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
304 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
306 for (i
= 0; i
< maxsize
; )
308 fprintf(log_stream
, "%4X: ", i
);
309 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
311 fprintf(log_stream
, "%02X ", d
[j
]);
313 fputs(": ", log_stream
);
316 for (; j
< i
+ 16; j
++)
318 fputs(" ", log_stream
);
320 fputs(": ", log_stream
);
323 fputs(" ", log_stream
);
324 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
326 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
327 fputc(d
[j
], log_stream
);
329 fputc('.', log_stream
);
332 fputs(" ", log_stream
);
336 fputs("\n", log_stream
);
340 setbuf(log_stream
, NULL
);
344 // update a counter, accumulating 2^32 wraps
345 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
347 uint32_t new = *counter
+ delta
;
354 // initialise the random generator
355 static void initrandom(char *source
)
357 static char path
[sizeof(config
->random_device
)] = "*undefined*";
359 // reinitialise only if we are forced to do so or if the config has changed
360 if (source
&& !strncmp(path
, source
, sizeof(path
)))
363 // close previous source, if any
372 snprintf(path
, sizeof(path
), "%s", source
);
376 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
378 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
379 path
, strerror(errno
));
384 // fill buffer with random data
385 void random_data(uint8_t *buf
, int len
)
392 n
= read(rand_fd
, buf
, len
);
393 if (n
>= len
) return;
398 LOG(0, 0, 0, "Error reading from random source: %s\n",
401 // fall back to rand()
409 // append missing data
411 // not using the low order bits from the prng stream
412 buf
[n
++] = (rand() >> 4) & 0xff;
417 // This adds it to the routing table, advertises it
418 // via BGP if enabled, and stuffs it into the
419 // 'sessionbyip' cache.
421 // 'ip' and 'mask' must be in _host_ order.
423 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
428 if (!mask
) mask
= 0xffffffff;
430 ip
&= mask
; // Force the ip to be the first one in the route.
432 memset(&r
, 0, sizeof(r
));
433 r
.rt_dev
= config
->tundevice
;
434 r
.rt_dst
.sa_family
= AF_INET
;
435 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
436 r
.rt_gateway
.sa_family
= AF_INET
;
437 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
438 r
.rt_genmask
.sa_family
= AF_INET
;
439 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
440 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
442 r
.rt_flags
|= RTF_GATEWAY
;
443 else if (mask
== 0xffffffff)
444 r
.rt_flags
|= RTF_HOST
;
446 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
447 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
448 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
450 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
451 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
455 bgp_add_route(htonl(ip
), htonl(mask
));
457 bgp_del_route(htonl(ip
), htonl(mask
));
460 // Add/Remove the IPs to the 'sessionbyip' cache.
461 // Note that we add the zero address in the case of
462 // a network route. Roll on CIDR.
464 // Note that 's == 0' implies this is the address pool.
465 // We still cache it here, because it will pre-fill
466 // the malloc'ed tree.
470 if (!add
) // Are we deleting a route?
471 s
= 0; // Caching the session as '0' is the same as uncaching.
473 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
478 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
481 char ipv6addr
[INET6_ADDRSTRLEN
];
485 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
489 memset(&rt
, 0, sizeof(rt
));
491 memcpy(&rt
.rtmsg_dst
, &ip
, sizeof(struct in6_addr
));
492 rt
.rtmsg_dst_len
= prefixlen
;
494 rt
.rtmsg_flags
= RTF_UP
;
495 rt
.rtmsg_ifindex
= tunidx
;
497 LOG(1, 0, 0, "Route %s %s/%d\n",
499 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
502 if (ioctl(ifr6fd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &rt
) < 0)
503 LOG(0, 0, 0, "route6set() error in ioctl: %s\n",
506 // FIXME: need to add BGP routing (RFC2858)
510 if (!add
) // Are we deleting a route?
511 s
= 0; // Caching the session as '0' is the same as uncaching.
513 cache_ipv6map(ip
, prefixlen
, s
);
520 // Set up netlink socket
521 static void initnetlink(void)
523 struct sockaddr_nl nladdr
;
525 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
528 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
532 memset(&nladdr
, 0, sizeof(nladdr
));
533 nladdr
.nl_family
= AF_NETLINK
;
534 nladdr
.nl_pid
= getpid();
536 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
538 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
543 static ssize_t
netlink_send(struct nlmsghdr
*nh
, int want_ack
)
545 struct sockaddr_nl nladdr
;
549 nh
->nlmsg_pid
= getpid();
550 nh
->nlmsg_seq
= ++nlseqnum
;
552 nh
->nlmsg_flags
|= NLM_F_ACK
;
554 // set kernel address
555 memset(&nladdr
, 0, sizeof(nladdr
));
556 nladdr
.nl_family
= AF_NETLINK
;
558 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
559 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
561 return sendmsg(nlfd
, &msg
, 0);
564 static ssize_t
netlink_recv(char *buf
, ssize_t len
)
566 struct sockaddr_nl nladdr
;
570 // set kernel address
571 memset(&nladdr
, 0, sizeof(nladdr
));
572 nladdr
.nl_family
= AF_NETLINK
;
574 iov
= (struct iovec
){ buf
, len
};
575 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
577 return recvmsg(nlfd
, &msg
, 0);
580 static ssize_t
netlink_check_ack(struct nlmsghdr
*ack_nh
, ssize_t len
, int msg_count
)
585 for (; NLMSG_OK (ack_nh
, len
); ack_nh
= NLMSG_NEXT (ack_nh
, len
))
587 if (ack_nh
->nlmsg_type
== NLMSG_DONE
)
588 return msg_count
!= 0 || seqnum
!= nlseqnum
;
591 if (ack_nh
->nlmsg_type
== NLMSG_ERROR
)
593 struct nlmsgerr
*errmsg
= NLMSG_DATA(ack_nh
);
595 return errmsg
->error
; // got an error back
600 if (errmsg
->msg
.nlmsg_seq
> seqnum
);
601 seqnum
= errmsg
->msg
.nlmsg_seq
;
602 // if this is a single message, return now
603 if (!(ack_nh
->nlmsg_flags
& NLM_F_MULTI
))
604 return msg_count
!= 0 || seqnum
!= nlseqnum
;
609 LOG(3, 0, 0, "Got an unknown netlink message: type %d\n", ack_nh
->nlmsg_type
);
612 return 1; // malformed message?!
616 // Set up TUN interface
617 static void inittun(void)
619 struct ifinfomsg ifinfo
;
623 struct nlmsghdr
*resp_nh
;
625 memset(&ifr
, 0, sizeof(ifr
));
626 ifr
.ifr_flags
= IFF_TUN
;
628 tunfd
= open(TUNDEVICE
, O_RDWR
);
631 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
635 int flags
= fcntl(tunfd
, F_GETFL
, 0);
636 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
638 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
640 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
643 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
644 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
647 // get the interface index
650 struct ifinfomsg ifinfo
__attribute__ ((aligned(NLMSG_ALIGNTO
)));
651 struct rtattr ifname_rta
__attribute__ ((aligned(RTA_ALIGNTO
)));
652 char ifname
[IFNAMSIZ
];
655 req
.nh
.nlmsg_type
= RTM_GETLINK
;
656 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
658 req
.ifinfo
.ifi_family
= AF_UNSPEC
; // as the man says
660 req
.ifname_rta
.rta_len
= RTA_LENGTH(strlen(config
->tundevice
)+1);
661 req
.ifname_rta
.rta_type
= IFLA_IFNAME
;
662 strncpy(req
.ifname
, config
->tundevice
, IFNAMSIZ
-1);
664 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifinfo
)
665 + req
.ifname_rta
.rta_len
);
667 if(netlink_send(&req
.nh
, 0) < 0 || (len
= netlink_recv(buf
, sizeof(buf
))) < 0)
669 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno
));
673 resp_nh
= (struct nlmsghdr
*)buf
;
674 if (!NLMSG_OK (resp_nh
, len
))
676 LOG(0, 0, 0, "Malformed answer getting tun ifindex\n");
680 memcpy(&ifinfo
, NLMSG_DATA(resp_nh
), sizeof(ifinfo
));
682 tunidx
= ifinfo
.ifi_index
;
690 struct ifinfomsg ifinfo
;
691 struct ifaddrmsg ifaddr
;
692 } ifmsg
__attribute__ ((aligned(NLMSG_ALIGNTO
)));
693 char rtdata
[32]; // 32 should be enough
697 uint32_t u32
__attribute__ ((aligned(RTA_ALIGNTO
)));;
701 struct in_addr addr
__attribute__ ((aligned(RTA_ALIGNTO
)));;
705 struct in6_addr addr6
__attribute__ ((aligned(RTA_ALIGNTO
)));;
711 memset(&req
, 0, sizeof(req
));
713 req
.nh
.nlmsg_type
= RTM_SETLINK
;
714 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
716 req
.ifmsg
.ifinfo
= ifinfo
;
717 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
718 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
720 buf_ptr
= NLMSG_DATA(&req
.nh
) + sizeof(req
.ifmsg
.ifinfo
);
722 u32_attr
.rta
.rta_len
= RTA_LENGTH(sizeof(u32_attr
.u32
));
723 u32_attr
.rta
.rta_type
= IFLA_TXQLEN
;
724 /* Bump up the qlen to deal with bursts from the network */
726 memcpy(buf_ptr
, &u32_attr
, sizeof(u32_attr
));
728 buf_ptr
+= RTA_ALIGN(u32_attr
.rta
.rta_len
);
730 u32_attr
.rta
.rta_len
= RTA_LENGTH(sizeof(u32_attr
.u32
));
731 u32_attr
.rta
.rta_type
= IFLA_MTU
;
732 /* set MTU to modem MRU */
734 memcpy(buf_ptr
, &u32_attr
, sizeof(u32_attr
));
736 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
)
737 + u32_attr
.rta
.rta_len
* 2);
739 if (netlink_send(&req
.nh
, 1) < 0)
741 LOG(0, 0, 0, "Error setting up tun device interface: %s\n", strerror(errno
));
745 memset(&req
, 0, sizeof(req
));
747 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
748 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_MULTI
;
750 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
751 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
752 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
754 ipv4_attr
.rta
.rta_len
= RTA_LENGTH(sizeof(ipv4_attr
.addr
));
755 ipv4_attr
.rta
.rta_type
= IFA_ADDRESS
;
756 ipv4_attr
.addr
.s_addr
= config
->bind_address
?
757 config
->bind_address
: 0x01010101; // 1.1.1.1
758 memcpy(NLMSG_DATA(&req
.nh
) + sizeof(req
.ifmsg
.ifaddr
), &ipv4_attr
, sizeof(ipv4_attr
));
760 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
)
761 + ipv4_attr
.rta
.rta_len
);
763 if (netlink_send(&req
.nh
, 1) < 0)
765 LOG(0, 0, 0, "Error setting up tun device IPv4 address: %s\n", strerror(errno
));
769 memset(&req
, 0, sizeof(req
));
771 // Only setup IPv6 on the tun device if we have a configured prefix
772 if (config
->ipv6_prefix
.s6_addr
[0]) {
773 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
774 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_MULTI
;
776 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
777 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
778 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
779 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
781 ipv6_attr
.rta
.rta_len
= RTA_LENGTH(sizeof(ipv6_attr
.addr6
));
782 ipv6_attr
.rta
.rta_type
= IFA_LOCAL
;
783 // Link local address is FE80::1
784 memset(&ipv6_attr
.addr6
, 0, sizeof(ipv6_attr
.addr6
));
785 ipv6_attr
.addr6
.s6_addr
[0] = 0xFE;
786 ipv6_attr
.addr6
.s6_addr
[1] = 0x80;
787 ipv6_attr
.addr6
.s6_addr
[15] = 1;
788 memcpy(NLMSG_DATA(&req
.nh
) + sizeof(req
.ifmsg
.ifaddr
), &ipv6_attr
, sizeof(ipv6_attr
));
790 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
)
791 + ipv6_attr
.rta
.rta_len
);
793 if (netlink_send(&req
.nh
, 1) < 0)
795 LOG(0, 0, 0, "Error setting up tun device IPv6 LL address: %s\n", strerror(errno
));
799 memset(&req
, 0, sizeof(req
));
801 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
802 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_MULTI
;
804 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
805 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
806 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
807 req
.ifmsg
.ifaddr
.ifa_index
= ifinfo
.ifi_index
;
809 ipv6_attr
.rta
.rta_len
= RTA_LENGTH(sizeof(ipv6_attr
.addr6
));
810 ipv6_attr
.rta
.rta_type
= IFA_LOCAL
;
811 // Global address is prefix::1
812 ipv6_attr
.addr6
= config
->ipv6_prefix
;
813 ipv6_attr
.addr6
.s6_addr
[15] = 1;
814 memcpy(NLMSG_DATA(&req
.nh
) + sizeof(req
.ifmsg
.ifaddr
), &ipv6_attr
, sizeof(ipv6_attr
));
816 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
)
817 + ipv6_attr
.rta
.rta_len
);
819 if (netlink_send(&req
.nh
, 1) < 0)
821 LOG(0, 0, 0, "Error setting up tun device IPv6 global address: %s\n", strerror(errno
));
825 memset(&req
, 0, sizeof(req
));
828 req
.nh
.nlmsg_type
= NLMSG_DONE
;
829 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
831 if (netlink_send(&req
.nh
, 1) < 0)
833 LOG(0, 0, 0, "Error finishing setting up tun device: %s\n", strerror(errno
));
838 buf_len
= sizeof(buf
);
841 len
= netlink_recv(buf_ptr
, sizeof(buf_len
));
844 LOG(0, 0, 0, "Error waiting for ack setting up tun device: %s\n", strerror(errno
));
848 resp_nh
= (struct nlmsghdr
*)buf_ptr
;
852 while (buf_len
> 0 && (resp_nh
->nlmsg_flags
& NLM_F_MULTI
)
853 && resp_nh
->nlmsg_type
!= NLMSG_DONE
);
855 if ((err
= netlink_check_ack((struct nlmsghdr
*)buf
, buf_len
, 4)))
858 LOG(0, 0, 0, "Error while receiving tun device ack: %s\n", strerror(errno
));
860 LOG(0, 0, 0, "Error while receiving tun device ack\n");
867 static void initudp(void)
870 struct sockaddr_in addr
;
873 memset(&addr
, 0, sizeof(addr
));
874 addr
.sin_family
= AF_INET
;
875 addr
.sin_port
= htons(L2TPPORT
);
876 addr
.sin_addr
.s_addr
= config
->bind_address
;
877 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
878 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
880 int flags
= fcntl(udpfd
, F_GETFL
, 0);
881 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
883 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
885 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
890 memset(&addr
, 0, sizeof(addr
));
891 addr
.sin_family
= AF_INET
;
892 addr
.sin_port
= htons(NSCTL_PORT
);
893 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
894 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
895 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
896 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
898 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
902 // Dynamic Authorization Extensions to RADIUS
903 memset(&addr
, 0, sizeof(addr
));
904 addr
.sin_family
= AF_INET
;
905 addr
.sin_port
= htons(config
->radius_dae_port
);
906 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
907 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
908 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
909 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
911 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
916 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
920 // Find session by IP, < 1 for not found
922 // Confusingly enough, this 'ip' must be
923 // in _network_ order. This being the common
924 // case when looking it up from IP packet headers.
926 // We actually use this cache for two things.
927 // #1. For used IP addresses, this maps to the
928 // session ID that it's used by.
929 // #2. For un-used IP addresses, this maps to the
930 // index into the pool table that contains that
934 static sessionidt
lookup_ipmap(in_addr_t ip
)
936 uint8_t *a
= (uint8_t *) &ip
;
937 union iphash
*h
= ip_hash
;
939 if (!(h
= h
[*a
++].idx
)) return 0;
940 if (!(h
= h
[*a
++].idx
)) return 0;
941 if (!(h
= h
[*a
++].idx
)) return 0;
946 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
948 struct ipv6radix
*curnode
;
951 char ipv6addr
[INET6_ADDRSTRLEN
];
953 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
957 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
959 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
964 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
965 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
972 sessionidt
sessionbyip(in_addr_t ip
)
974 sessionidt s
= lookup_ipmap(ip
);
977 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
983 sessionidt
sessionbyipv6(struct in6_addr ip
)
986 CSTAT(sessionbyipv6
);
988 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
989 (ip
.s6_addr
[0] == 0xFE &&
990 ip
.s6_addr
[1] == 0x80 &&
991 ip
.s6_addr16
[1] == 0 &&
992 ip
.s6_addr16
[2] == 0 &&
993 ip
.s6_addr16
[3] == 0)) {
994 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
996 s
= lookup_ipv6map(ip
);
999 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1006 // Take an IP address in HOST byte order and
1007 // add it to the sessionid by IP cache.
1009 // (It's actually cached in network order)
1011 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
1013 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
1014 uint8_t *a
= (uint8_t *) &nip
;
1015 union iphash
*h
= ip_hash
;
1018 for (i
= 0; i
< 3; i
++)
1020 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1029 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1032 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1033 // else a map to an ip pool index.
1036 static void uncache_ipmap(in_addr_t ip
)
1038 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1041 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1045 struct ipv6radix
*curnode
;
1046 char ipv6addr
[INET6_ADDRSTRLEN
];
1048 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
1050 bytes
= prefixlen
>> 3;
1053 if (curnode
->branch
== NULL
)
1055 if (!(curnode
->branch
= calloc(256,
1056 sizeof (struct ipv6radix
))))
1059 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1066 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1067 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1071 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1072 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1078 // CLI list to dump current ipcache.
1080 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1082 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1086 if (CLI_HELP_REQUESTED
)
1087 return CLI_HELP_NO_ARGS
;
1089 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1091 for (i
= 0; i
< 256; ++i
)
1097 for (j
= 0; j
< 256; ++j
)
1103 for (k
= 0; k
< 256; ++k
)
1109 for (l
= 0; l
< 256; ++l
)
1114 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1120 cli_print(cli
, "%d entries in cache", count
);
1125 // Find session by username, 0 for not found
1126 // walled garden users aren't authenticated, so the username is
1127 // reasonably useless. Ignore them to avoid incorrect actions
1129 // This is VERY inefficent. Don't call it often. :)
1131 sessionidt
sessionbyuser(char *username
)
1134 CSTAT(sessionbyuser
);
1136 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1138 if (!session
[s
].opened
)
1141 if (session
[s
].walled_garden
)
1142 continue; // Skip walled garden users.
1144 if (!strncmp(session
[s
].user
, username
, 128))
1148 return 0; // Not found.
1151 void send_garp(in_addr_t ip
)
1157 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1160 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1163 memset(&ifr
, 0, sizeof(ifr
));
1164 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1165 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1167 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1171 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1172 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1174 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1179 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1182 static sessiont
*sessiontbysessionidt(sessionidt s
)
1184 if (!s
|| s
>= MAXSESSION
) return NULL
;
1188 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1190 sessionidt val
= s
-session
;
1191 if (s
< session
|| val
>= MAXSESSION
) return 0;
1195 // actually send a control message for a specific tunnel
1196 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1198 struct sockaddr_in addr
;
1204 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1205 STAT(tunnel_tx_errors
);
1211 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1212 STAT(tunnel_tx_errors
);
1216 memset(&addr
, 0, sizeof(addr
));
1217 addr
.sin_family
= AF_INET
;
1218 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1219 addr
.sin_port
= htons(tunnel
[t
].port
);
1221 // sequence expected, if sequence in message
1222 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1224 // If this is a control message, deal with retries
1227 tunnel
[t
].last
= time_now
; // control message sent
1228 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1231 STAT(tunnel_retries
);
1232 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1236 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1238 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1239 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1240 STAT(tunnel_tx_errors
);
1244 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1245 STAT(tunnel_tx_packets
);
1246 INC_STAT(tunnel_tx_bytes
, l
);
1250 // Tiny helper function to write data to
1251 // the 'tun' device.
1253 int tun_write(uint8_t * data
, int size
)
1255 return write(tunfd
, data
, size
);
1258 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1259 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1261 int d
= (tcp
[12] >> 4) * 4;
1268 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1271 if (tcp
+ d
> buf
+ len
) // short?
1279 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1282 if (mss
+ 2 > data
) return; // short?
1286 if (*opts
== 0) return; // end of options
1287 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1290 opts
+= opts
[1]; // skip over option
1293 if (!mss
) return; // not found
1294 orig
= ntohs(*(uint16_t *) mss
);
1296 if (orig
<= MSS
) return; // mss OK
1298 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1299 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1300 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1301 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1304 *(int16_t *) mss
= htons(MSS
);
1306 // adjust checksum (see rfc1141)
1307 sum
= orig
+ (~MSS
& 0xffff);
1308 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1309 sum
= (sum
& 0xffff) + (sum
>> 16);
1310 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1313 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1317 // Skip the four extra bytes
1329 proto
= ntohs(*(uint16_t *) p
);
1337 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1338 return; // closing session, PPP not processed
1340 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1341 processipin(s
, t
, p
, l
);
1343 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1347 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1348 return; // closing session, PPP not processed
1351 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1352 processipv6in(s
, t
, p
, l
);
1354 else if (proto
== PPPIPCP
)
1356 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1357 processipcp(s
, t
, p
, l
);
1359 else if (proto
== PPPCCP
)
1361 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1362 processccp(s
, t
, p
, l
);
1366 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1370 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1372 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1373 sp
->cout_delta
+= len
;
1375 sp
->last_data
= time_now
;
1377 sess_local
[s
].cout
+= len
; // To send to master..
1378 sess_local
[s
].pout
++;
1381 // process outgoing (to tunnel) IP
1383 static void processipout(uint8_t *buf
, int len
)
1390 uint8_t *data
= buf
; // Keep a copy of the originals.
1393 uint8_t fragbuf
[MAXETHER
+ 20];
1395 CSTAT(processipout
);
1397 if (len
< MIN_IP_SIZE
)
1399 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1400 STAT(tun_rx_errors
);
1403 if (len
>= MAXETHER
)
1405 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1406 STAT(tun_rx_errors
);
1410 // Skip the tun header
1414 // Got an IP header now
1415 if (*(uint8_t *)(buf
) >> 4 != 4)
1417 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1421 ip
= *(uint32_t *)(buf
+ 16);
1422 if (!(s
= sessionbyip(ip
)))
1424 // Is this a packet for a session that doesn't exist?
1425 static int rate
= 0; // Number of ICMP packets we've sent this second.
1426 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1428 if (last
!= time_now
)
1434 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1436 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1437 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1438 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1443 t
= session
[s
].tunnel
;
1444 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1446 LOG(3, s
, t
, "Packet size more than session MRU\n");
1452 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1453 if (config
->max_packets
> 0)
1455 if (sess_local
[s
].last_packet_out
== TIME
)
1457 int max
= config
->max_packets
;
1459 // All packets for throttled sessions are handled by the
1460 // master, so further limit by using the throttle rate.
1461 // A bit of a kludge, since throttle rate is in kbps,
1462 // but should still be generous given our average DSL
1463 // packet size is 200 bytes: a limit of 28kbps equates
1464 // to around 180 packets per second.
1465 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1466 max
= sp
->throttle_out
;
1468 if (++sess_local
[s
].packets_out
> max
)
1470 sess_local
[s
].packets_dropped
++;
1476 if (sess_local
[s
].packets_dropped
)
1478 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1479 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1480 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1481 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1485 sess_local
[s
].last_packet_out
= TIME
;
1486 sess_local
[s
].packets_out
= 1;
1487 sess_local
[s
].packets_dropped
= 0;
1491 // run access-list if any
1492 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1495 // adjust MSS on SYN and SYN,ACK packets with options
1496 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1498 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1499 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1500 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1505 // Are we throttling this session?
1506 if (config
->cluster_iam_master
)
1507 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1509 master_throttle_packet(sp
->tbf_out
, data
, size
);
1513 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1515 // We are walled-gardening this
1516 master_garden_packet(s
, data
, size
);
1520 // Add on L2TP header
1523 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1525 bid
= session
[s
].bundle
;
1526 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1527 t
= session
[s
].tunnel
;
1529 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1530 if(len
> MINFRAGLEN
)
1532 // Partition the packet to "bundle[b].num_of_links" fragments
1533 bundlet
*b
= &bundle
[bid
];
1534 uint32_t num_of_links
= b
->num_of_links
;
1535 uint32_t fraglen
= len
/ num_of_links
;
1536 fraglen
= (fraglen
> session
[s
].mru
? session
[s
].mru
: fraglen
);
1537 uint32_t last_fraglen
= fraglen
+ len
% num_of_links
;
1538 last_fraglen
= (last_fraglen
> session
[s
].mru
? len
% num_of_links
: last_fraglen
);
1539 uint32_t remain
= len
;
1541 // send the first packet
1542 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1544 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1546 update_session_out_stat(s
, sp
, fraglen
);
1548 while (remain
> last_fraglen
)
1550 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1551 t
= session
[s
].tunnel
;
1553 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1554 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1556 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1557 update_session_out_stat(s
, sp
, fraglen
);
1560 // send the last fragment
1561 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1562 t
= session
[s
].tunnel
;
1564 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1565 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1567 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1568 update_session_out_stat(s
, sp
, remain
);
1569 if (remain
!= last_fraglen
)
1570 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1573 // Send it as one frame
1574 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1576 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1577 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1578 update_session_out_stat(s
, sp
, len
);
1583 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1585 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1586 update_session_out_stat(s
, sp
, len
);
1590 // Snooping this session, send it to intercept box
1591 if (sp
->snoop_ip
&& sp
->snoop_port
)
1592 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1597 // process outgoing (to tunnel) IPv6
1599 static void processipv6out(uint8_t * buf
, int len
)
1605 struct in6_addr ip6
;
1607 uint8_t *data
= buf
; // Keep a copy of the originals.
1610 uint8_t b
[MAXETHER
+ 20];
1612 CSTAT(processipv6out
);
1614 if (len
< MIN_IP_SIZE
)
1616 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1617 STAT(tunnel_tx_errors
);
1620 if (len
>= MAXETHER
)
1622 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1623 STAT(tunnel_tx_errors
);
1627 // Skip the tun header
1631 // Got an IP header now
1632 if (*(uint8_t *)(buf
) >> 4 != 6)
1634 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1638 ip6
= *(struct in6_addr
*)(buf
+24);
1639 s
= sessionbyipv6(ip6
);
1643 ip
= *(uint32_t *)(buf
+ 32);
1644 s
= sessionbyip(ip
);
1649 // Is this a packet for a session that doesn't exist?
1650 static int rate
= 0; // Number of ICMP packets we've sent this second.
1651 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1653 if (last
!= time_now
)
1659 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1661 // FIXME: Should send icmp6 host unreachable
1665 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1667 bundleidt bid
= session
[s
].bundle
;
1668 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1669 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1671 t
= session
[s
].tunnel
;
1673 sp
->last_data
= time_now
;
1675 // FIXME: add DoS prevention/filters?
1679 // Are we throttling this session?
1680 if (config
->cluster_iam_master
)
1681 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1683 master_throttle_packet(sp
->tbf_out
, data
, size
);
1686 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1688 // We are walled-gardening this
1689 master_garden_packet(s
, data
, size
);
1693 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1695 // Add on L2TP header
1697 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1699 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1702 // Snooping this session, send it to intercept box
1703 if (sp
->snoop_ip
&& sp
->snoop_port
)
1704 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1706 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1707 sp
->cout_delta
+= len
;
1711 sess_local
[s
].cout
+= len
; // To send to master..
1712 sess_local
[s
].pout
++;
1716 // Helper routine for the TBF filters.
1717 // Used to send queued data in to the user!
1719 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1725 uint8_t b
[MAXETHER
+ 20];
1727 if (len
< 0 || len
> MAXETHER
)
1729 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1733 // Skip the tun header
1737 ip
= *(in_addr_t
*)(buf
+ 16);
1742 t
= session
[s
].tunnel
;
1745 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1747 // Add on L2TP header
1749 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1751 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1754 // Snooping this session.
1755 if (sp
->snoop_ip
&& sp
->snoop_port
)
1756 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1758 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1759 sp
->cout_delta
+= len
;
1763 sess_local
[s
].cout
+= len
; // To send to master..
1764 sess_local
[s
].pout
++;
1767 // add an AVP (16 bit)
1768 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1770 uint16_t l
= (m
? 0x8008 : 0x0008);
1771 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1772 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1773 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1774 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1778 // add an AVP (32 bit)
1779 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1781 uint16_t l
= (m
? 0x800A : 0x000A);
1782 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1783 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1784 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1785 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1789 // add an AVP (string)
1790 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1792 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1793 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1794 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1795 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1796 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1797 c
->length
+= 6 + strlen(val
);
1801 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1803 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1804 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1805 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1806 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1807 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1808 c
->length
+= 6 + len
;
1811 // new control connection
1812 static controlt
*controlnew(uint16_t mtype
)
1816 c
= malloc(sizeof(controlt
));
1820 controlfree
= c
->next
;
1824 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1826 control16(c
, 0, mtype
, 1);
1830 // send zero block if nothing is waiting
1832 static void controlnull(tunnelidt t
)
1835 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1838 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1839 *(uint16_t *) (buf
+ 2) = htons(12); // length
1840 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1841 *(uint16_t *) (buf
+ 6) = htons(0); // session
1842 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1843 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1844 tunnelsend(buf
, 12, t
);
1847 // add a control message to a tunnel, and send if within window
1848 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1850 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1851 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1852 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1853 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1854 tunnel
[t
].ns
++; // advance sequence
1855 // link in message in to queue
1856 if (tunnel
[t
].controlc
)
1857 tunnel
[t
].controle
->next
= c
;
1859 tunnel
[t
].controls
= c
;
1861 tunnel
[t
].controle
= c
;
1862 tunnel
[t
].controlc
++;
1864 // send now if space in window
1865 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1867 tunnel
[t
].try = 0; // first send
1868 tunnelsend(c
->buf
, c
->length
, t
);
1873 // Throttle or Unthrottle a session
1875 // Throttle the data from/to through a session to no more than
1876 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1879 // If either value is -1, the current value is retained for that
1882 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1884 if (!session
[s
].opened
)
1885 return; // No-one home.
1887 if (!*session
[s
].user
)
1888 return; // User not logged in
1892 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1893 if (session
[s
].tbf_in
)
1894 free_tbf(session
[s
].tbf_in
);
1897 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1899 session
[s
].tbf_in
= 0;
1901 session
[s
].throttle_in
= rate_in
;
1906 int bytes
= rate_out
* 1024 / 8;
1907 if (session
[s
].tbf_out
)
1908 free_tbf(session
[s
].tbf_out
);
1911 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1913 session
[s
].tbf_out
= 0;
1915 session
[s
].throttle_out
= rate_out
;
1919 // add/remove filters from session (-1 = no change)
1920 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1922 if (!session
[s
].opened
)
1923 return; // No-one home.
1925 if (!*session
[s
].user
)
1926 return; // User not logged in
1929 if (filter_in
> MAXFILTER
) filter_in
= -1;
1930 if (filter_out
> MAXFILTER
) filter_out
= -1;
1931 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1932 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1936 if (session
[s
].filter_in
)
1937 ip_filters
[session
[s
].filter_in
- 1].used
--;
1940 ip_filters
[filter_in
- 1].used
++;
1942 session
[s
].filter_in
= filter_in
;
1945 if (filter_out
>= 0)
1947 if (session
[s
].filter_out
)
1948 ip_filters
[session
[s
].filter_out
- 1].used
--;
1951 ip_filters
[filter_out
- 1].used
++;
1953 session
[s
].filter_out
= filter_out
;
1957 // start tidy shutdown of session
1958 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1960 int walled_garden
= session
[s
].walled_garden
;
1961 bundleidt b
= session
[s
].bundle
;
1962 //delete routes only for last session in bundle (in case of MPPP)
1963 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1965 CSTAT(sessionshutdown
);
1967 if (!session
[s
].opened
)
1969 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1970 return; // not a live session
1973 if (!session
[s
].die
)
1975 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1976 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1977 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1978 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1981 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1983 // RADIUS Stop message
1984 uint16_t r
= radiusnew(s
);
1987 // stop, if not already trying
1988 if (radius
[r
].state
!= RADIUSSTOP
)
1990 radius
[r
].term_cause
= term_cause
;
1991 radius
[r
].term_msg
= reason
;
1992 radiussend(r
, RADIUSSTOP
);
1996 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1998 // Save counters to dump to accounting file
1999 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2000 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2004 { // IP allocated, clear and unroute
2007 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2009 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
2010 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
2013 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
2014 session
[s
].route
[r
].ip
= 0;
2017 if (session
[s
].ip_pool_index
== -1) // static ip
2019 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2025 // unroute IPv6, if setup
2026 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
2027 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2031 // This session was part of a bundle
2032 bundle
[b
].num_of_links
--;
2033 LOG(3, s
, 0, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2034 if(bundle
[b
].num_of_links
== 0)
2037 LOG(3, s
, 0, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2041 // Adjust the members array to accomodate the new change
2042 uint8_t mem_num
= 0;
2043 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2044 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2047 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2048 if(bundle
[b
].members
[ml
] == s
)
2053 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2054 LOG(3, s
, 0, "MPPP: Adjusted member links array\n");
2057 cluster_send_bundle(b
);
2061 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2062 throttle_session(s
, 0, 0);
2066 controlt
*c
= controlnew(14); // sending CDN
2070 *(uint16_t *) buf
= htons(cdn_result
);
2071 *(uint16_t *) (buf
+2) = htons(cdn_error
);
2072 controlb(c
, 1, buf
, 4, 1);
2075 control16(c
, 1, cdn_result
, 1);
2077 control16(c
, 14, s
, 1); // assigned session (our end)
2078 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2081 // update filter refcounts
2082 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2083 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2086 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2087 sess_local
[s
].lcp
.restart
= 0;
2088 sess_local
[s
].ipcp
.restart
= 0;
2089 sess_local
[s
].ipv6cp
.restart
= 0;
2090 sess_local
[s
].ccp
.restart
= 0;
2092 cluster_send_session(s
);
2095 void sendipcp(sessionidt s
, tunnelidt t
)
2097 uint8_t buf
[MAXETHER
];
2101 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2103 if (!session
[s
].unique_id
)
2105 if (!++last_id
) ++last_id
; // skip zero
2106 session
[s
].unique_id
= last_id
;
2109 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2113 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2114 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2115 q
[4] = 3; // ip address option
2116 q
[5] = 6; // option length
2117 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2118 config
->bind_address
? config
->bind_address
:
2119 my_address
; // send my IP
2121 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2122 restart_timer(s
, ipcp
);
2125 void sendipv6cp(sessionidt s
, tunnelidt t
)
2127 uint8_t buf
[MAXETHER
];
2131 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2133 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2137 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2138 // only send one type
2140 *(uint16_t *) (q
+ 2) = htons(14);
2141 q
[4] = 1; // interface identifier option
2142 q
[5] = 10; // option length
2143 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2144 *(uint32_t *) (q
+ 10) = 0;
2147 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2148 restart_timer(s
, ipv6cp
);
2151 static void sessionclear(sessionidt s
)
2153 memset(&session
[s
], 0, sizeof(session
[s
]));
2154 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2155 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2157 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2158 session
[s
].next
= sessionfree
;
2162 // kill a session now
2163 void sessionkill(sessionidt s
, char *reason
)
2167 if (!session
[s
].opened
) // not alive
2170 if (session
[s
].next
)
2172 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2176 if (!session
[s
].die
)
2177 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2179 if (sess_local
[s
].radius
)
2180 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2182 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2184 cluster_send_session(s
);
2187 static void tunnelclear(tunnelidt t
)
2190 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2191 tunnel
[t
].state
= TUNNELFREE
;
2194 static void bundleclear(bundleidt b
)
2197 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2198 bundle
[b
].state
= BUNDLEFREE
;
2201 // kill a tunnel now
2202 static void tunnelkill(tunnelidt t
, char *reason
)
2209 tunnel
[t
].state
= TUNNELDIE
;
2211 // free control messages
2212 while ((c
= tunnel
[t
].controls
))
2214 controlt
* n
= c
->next
;
2215 tunnel
[t
].controls
= n
;
2216 tunnel
[t
].controlc
--;
2217 c
->next
= controlfree
;
2221 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2222 if (session
[s
].tunnel
== t
)
2223 sessionkill(s
, reason
);
2227 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2228 cli_tunnel_actions
[t
].action
= 0;
2229 cluster_send_tunnel(t
);
2232 // shut down a tunnel cleanly
2233 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2237 CSTAT(tunnelshutdown
);
2239 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2241 // never set up, can immediately kill
2242 tunnelkill(t
, reason
);
2245 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2248 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2249 if (session
[s
].tunnel
== t
)
2250 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2252 tunnel
[t
].state
= TUNNELDIE
;
2253 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2254 cluster_send_tunnel(t
);
2255 // TBA - should we wait for sessions to stop?
2258 controlt
*c
= controlnew(4); // sending StopCCN
2263 *(uint16_t *) buf
= htons(result
);
2264 *(uint16_t *) (buf
+2) = htons(error
);
2267 int m
= strlen(msg
);
2268 if (m
+ 4 > sizeof(buf
))
2269 m
= sizeof(buf
) - 4;
2271 memcpy(buf
+4, msg
, m
);
2275 controlb(c
, 1, buf
, l
, 1);
2278 control16(c
, 1, result
, 1);
2280 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2281 controladd(c
, 0, t
); // send the message
2285 // read and process packet on tunnel (UDP)
2286 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2288 uint8_t *chapresponse
= NULL
;
2289 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2290 uint8_t *p
= buf
+ 2;
2297 LOG_HEX(5, "UDP Data", buf
, len
);
2298 STAT(tunnel_rx_packets
);
2299 INC_STAT(tunnel_rx_bytes
, len
);
2302 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2303 STAT(tunnel_rx_errors
);
2306 if ((buf
[1] & 0x0F) != 2)
2308 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2309 STAT(tunnel_rx_errors
);
2314 l
= ntohs(*(uint16_t *) p
);
2317 t
= ntohs(*(uint16_t *) p
);
2319 s
= ntohs(*(uint16_t *) p
);
2321 if (s
>= MAXSESSION
)
2323 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2324 STAT(tunnel_rx_errors
);
2329 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2330 STAT(tunnel_rx_errors
);
2335 ns
= ntohs(*(uint16_t *) p
);
2337 nr
= ntohs(*(uint16_t *) p
);
2342 uint16_t o
= ntohs(*(uint16_t *) p
);
2347 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2348 STAT(tunnel_rx_errors
);
2353 // used to time out old tunnels
2354 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2355 tunnel
[t
].lastrec
= time_now
;
2359 uint16_t message
= 0xFFFF; // message type
2361 uint8_t mandatory
= 0;
2362 uint16_t asession
= 0; // assigned session
2363 uint32_t amagic
= 0; // magic number
2364 uint8_t aflags
= 0; // flags from last LCF
2365 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2366 char called
[MAXTEL
] = ""; // called number
2367 char calling
[MAXTEL
] = ""; // calling number
2369 if (!config
->cluster_iam_master
)
2371 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2375 // control messages must have bits 0x80|0x40|0x08
2376 // (type, length and sequence) set, and bits 0x02|0x01
2377 // (offset and priority) clear
2378 if ((*buf
& 0xCB) != 0xC8)
2380 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2381 STAT(tunnel_rx_errors
);
2385 // check for duplicate tunnel open message
2391 // Is this a duplicate of the first packet? (SCCRQ)
2393 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2395 if (tunnel
[i
].state
!= TUNNELOPENING
||
2396 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2397 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2400 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2405 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2406 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2408 // if no tunnel specified, assign one
2411 if (!(t
= new_tunnel()))
2413 LOG(1, 0, 0, "No more tunnels\n");
2414 STAT(tunnel_overflow
);
2418 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2419 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2420 tunnel
[t
].window
= 4; // default window
2421 STAT(tunnel_created
);
2422 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2423 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2426 // If the 'ns' just received is not the 'nr' we're
2427 // expecting, just send an ack and drop it.
2429 // if 'ns' is less, then we got a retransmitted packet.
2430 // if 'ns' is greater than missed a packet. Either way
2431 // we should ignore it.
2432 if (ns
!= tunnel
[t
].nr
)
2434 // is this the sequence we were expecting?
2435 STAT(tunnel_rx_errors
);
2436 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2437 t
, ns
, tunnel
[t
].nr
);
2439 if (l
) // Is this not a ZLB?
2444 // check sequence of this message
2446 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2447 // some to clear maybe?
2448 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2450 controlt
*c
= tunnel
[t
].controls
;
2451 tunnel
[t
].controls
= c
->next
;
2452 tunnel
[t
].controlc
--;
2453 c
->next
= controlfree
;
2456 tunnel
[t
].try = 0; // we have progress
2459 // receiver advance (do here so quoted correctly in any sends below)
2460 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2461 if (skip
< 0) skip
= 0;
2462 if (skip
< tunnel
[t
].controlc
)
2464 // some control packets can now be sent that were previous stuck out of window
2465 int tosend
= tunnel
[t
].window
- skip
;
2466 controlt
*c
= tunnel
[t
].controls
;
2474 tunnel
[t
].try = 0; // first send
2475 tunnelsend(c
->buf
, c
->length
, t
);
2480 if (!tunnel
[t
].controlc
)
2481 tunnel
[t
].retry
= 0; // caught up
2484 { // if not a null message
2489 // Default disconnect cause/message on receipt of CDN. Set to
2490 // more specific value from attribute 1 (result code) or 46
2491 // (disconnect cause) if present below.
2492 int disc_cause_set
= 0;
2493 int disc_cause
= TERM_NAS_REQUEST
;
2494 char const *disc_reason
= "Closed (Received CDN).";
2497 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2499 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2506 LOG(1, s
, t
, "Invalid length in AVP\n");
2507 STAT(tunnel_rx_errors
);
2512 if (flags
& 0x3C) // reserved bits, should be clear
2514 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2516 result
= 2; // general error
2517 error
= 3; // reserved field non-zero
2522 if (*(uint16_t *) (b
))
2524 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2526 result
= 2; // general error
2527 error
= 6; // generic vendor-specific error
2528 msg
= "unsupported vendor-specific";
2532 mtype
= ntohs(*(uint16_t *) (b
));
2540 // handle hidden AVPs
2541 if (!*config
->l2tp_secret
)
2543 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2545 result
= 2; // general error
2546 error
= 6; // generic vendor-specific error
2547 msg
= "secret not specified";
2550 if (!session
[s
].random_vector_length
)
2552 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2554 result
= 2; // general error
2555 error
= 6; // generic
2556 msg
= "no random vector";
2561 LOG(2, s
, t
, "Short hidden AVP.\n");
2563 result
= 2; // general error
2564 error
= 2; // length is wrong
2570 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2572 orig_len
= ntohs(*(uint16_t *) b
);
2573 if (orig_len
> n
+ 2)
2575 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2579 result
= 2; // general error
2580 error
= 2; // length is wrong
2589 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2590 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2594 case 0: // message type
2595 message
= ntohs(*(uint16_t *) b
);
2596 mandatory
= flags
& 0x80;
2597 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2599 case 1: // result code
2601 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2602 char const *resdesc
= "(unknown)";
2603 char const *errdesc
= NULL
;
2608 resdesc
= l2tp_stopccn_result_code(rescode
);
2609 cause
= TERM_LOST_SERVICE
;
2611 else if (message
== 14)
2613 resdesc
= l2tp_cdn_result_code(rescode
);
2615 cause
= TERM_LOST_CARRIER
;
2617 cause
= TERM_ADMIN_RESET
;
2620 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2623 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2624 errdesc
= l2tp_error_code(errcode
);
2625 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2628 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2630 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2632 disc_cause_set
= mtype
;
2633 disc_reason
= errdesc
? errdesc
: resdesc
;
2640 case 2: // protocol version
2642 version
= ntohs(*(uint16_t *) (b
));
2643 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2644 if (version
&& version
!= 0x0100)
2645 { // allow 0.0 and 1.0
2646 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2648 result
= 5; // unspported protocol version
2649 error
= 0x0100; // supported version
2655 case 3: // framing capabilities
2657 case 4: // bearer capabilities
2659 case 5: // tie breaker
2660 // We never open tunnels, so we don't care about tie breakers
2662 case 6: // firmware revision
2664 case 7: // host name
2665 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2666 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2667 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2668 // TBA - to send to RADIUS
2670 case 8: // vendor name
2671 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2672 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2673 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2675 case 9: // assigned tunnel
2676 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2677 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2679 case 10: // rx window
2680 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2681 if (!tunnel
[t
].window
)
2682 tunnel
[t
].window
= 1; // window of 0 is silly
2683 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2685 case 11: // Challenge
2687 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2688 build_chap_response(b
, 2, n
, &chapresponse
);
2691 case 13: // Response
2692 // Why did they send a response? We never challenge.
2693 LOG(2, s
, t
, " received unexpected challenge response\n");
2696 case 14: // assigned session
2697 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2698 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2700 case 15: // call serial number
2701 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2703 case 18: // bearer type
2704 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2707 case 19: // framing type
2708 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2711 case 21: // called number
2712 memset(called
, 0, sizeof(called
));
2713 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2714 LOG(4, s
, t
, " Called <%s>\n", called
);
2716 case 22: // calling number
2717 memset(calling
, 0, sizeof(calling
));
2718 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2719 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2723 case 24: // tx connect speed
2726 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2730 // AS5300s send connect speed as a string
2732 memset(tmp
, 0, sizeof(tmp
));
2733 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2734 session
[s
].tx_connect_speed
= atol(tmp
);
2736 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2738 case 38: // rx connect speed
2741 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2745 // AS5300s send connect speed as a string
2747 memset(tmp
, 0, sizeof(tmp
));
2748 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2749 session
[s
].rx_connect_speed
= atol(tmp
);
2751 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2753 case 25: // Physical Channel ID
2755 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2756 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2759 case 29: // Proxy Authentication Type
2761 uint16_t atype
= ntohs(*(uint16_t *)b
);
2762 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2765 case 30: // Proxy Authentication Name
2768 memset(authname
, 0, sizeof(authname
));
2769 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2770 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2774 case 31: // Proxy Authentication Challenge
2776 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2779 case 32: // Proxy Authentication ID
2781 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2782 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2785 case 33: // Proxy Authentication Response
2786 LOG(4, s
, t
, " Proxy Auth Response\n");
2788 case 27: // last sent lcp
2789 { // find magic number
2790 uint8_t *p
= b
, *e
= p
+ n
;
2791 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2793 if (*p
== 5 && p
[1] == 6) // Magic-Number
2794 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2795 else if (*p
== 7) // Protocol-Field-Compression
2796 aflags
|= SESSION_PFC
;
2797 else if (*p
== 8) // Address-and-Control-Field-Compression
2798 aflags
|= SESSION_ACFC
;
2803 case 28: // last recv lcp confreq
2805 case 26: // Initial Received LCP CONFREQ
2807 case 39: // seq required - we control it as an LNS anyway...
2809 case 36: // Random Vector
2810 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2811 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2812 if (n
> sizeof(session
[s
].random_vector
))
2813 n
= sizeof(session
[s
].random_vector
);
2814 memcpy(session
[s
].random_vector
, b
, n
);
2815 session
[s
].random_vector_length
= n
;
2817 case 46: // ppp disconnect cause
2820 uint16_t code
= ntohs(*(uint16_t *) b
);
2821 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2822 uint8_t dir
= *(b
+ 4);
2824 LOG(4, s
, t
, " PPP disconnect cause "
2825 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2826 code
, proto
, dir
, n
- 5, b
+ 5);
2828 disc_cause_set
= mtype
;
2832 case 1: // admin disconnect
2833 disc_cause
= TERM_ADMIN_RESET
;
2834 disc_reason
= "Administrative disconnect";
2836 case 3: // lcp terminate
2837 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2838 disc_cause
= TERM_USER_REQUEST
;
2839 disc_reason
= "Normal disconnection";
2841 case 4: // compulsory encryption unavailable
2842 if (dir
!= 1) break; // 1=refused by peer, 2=local
2843 disc_cause
= TERM_USER_ERROR
;
2844 disc_reason
= "Compulsory encryption refused";
2846 case 5: // lcp: fsm timeout
2847 disc_cause
= TERM_PORT_ERROR
;
2848 disc_reason
= "LCP: FSM timeout";
2850 case 6: // lcp: no recognisable lcp packets received
2851 disc_cause
= TERM_PORT_ERROR
;
2852 disc_reason
= "LCP: no recognisable LCP packets";
2854 case 7: // lcp: magic-no error (possibly looped back)
2855 disc_cause
= TERM_PORT_ERROR
;
2856 disc_reason
= "LCP: magic-no error (possible loop)";
2858 case 8: // lcp: echo request timeout
2859 disc_cause
= TERM_PORT_ERROR
;
2860 disc_reason
= "LCP: echo request timeout";
2862 case 13: // auth: fsm timeout
2863 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2864 disc_reason
= "Authentication: FSM timeout";
2866 case 15: // auth: unacceptable auth protocol
2867 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2868 disc_reason
= "Unacceptable authentication protocol";
2870 case 16: // auth: authentication failed
2871 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2872 disc_reason
= "Authentication failed";
2874 case 17: // ncp: fsm timeout
2875 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2876 disc_reason
= "NCP: FSM timeout";
2878 case 18: // ncp: no ncps available
2879 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2880 disc_reason
= "NCP: no NCPs available";
2882 case 19: // ncp: failure to converge on acceptable address
2883 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2884 disc_reason
= (dir
== 1)
2885 ? "NCP: too many Configure-Naks received from peer"
2886 : "NCP: too many Configure-Naks sent to peer";
2888 case 20: // ncp: user not permitted to use any address
2889 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2890 disc_reason
= (dir
== 1)
2891 ? "NCP: local link address not acceptable to peer"
2892 : "NCP: remote link address not acceptable";
2899 static char e
[] = "unknown AVP 0xXXXX";
2900 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2902 result
= 2; // general error
2903 error
= 8; // unknown mandatory AVP
2904 sprintf((msg
= e
) + 14, "%04x", mtype
);
2911 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2915 case 1: // SCCRQ - Start Control Connection Request
2916 tunnel
[t
].state
= TUNNELOPENING
;
2917 if (main_quit
!= QUIT_SHUTDOWN
)
2919 controlt
*c
= controlnew(2); // sending SCCRP
2920 control16(c
, 2, version
, 1); // protocol version
2921 control32(c
, 3, 3, 1); // framing
2922 controls(c
, 7, hostname
, 1); // host name
2923 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2924 control16(c
, 9, t
, 1); // assigned tunnel
2925 controladd(c
, 0, t
); // send the resply
2929 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2933 tunnel
[t
].state
= TUNNELOPEN
;
2934 tunnel
[t
].lastrec
= time_now
;
2937 tunnel
[t
].state
= TUNNELOPEN
;
2938 tunnel
[t
].lastrec
= time_now
;
2939 controlnull(t
); // ack
2942 controlnull(t
); // ack
2943 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2946 controlnull(t
); // simply ACK
2958 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2960 controlt
*c
= controlnew(11); // ICRP
2963 sessionfree
= session
[s
].next
;
2964 memset(&session
[s
], 0, sizeof(session
[s
]));
2966 if (s
> config
->cluster_highest_sessionid
)
2967 config
->cluster_highest_sessionid
= s
;
2969 session
[s
].opened
= time_now
;
2970 session
[s
].tunnel
= t
;
2971 session
[s
].far
= asession
;
2972 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2973 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2974 control16(c
, 14, s
, 1); // assigned session
2975 controladd(c
, asession
, t
); // send the reply
2977 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2978 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2980 session
[s
].ppp
.phase
= Establish
;
2981 session
[s
].ppp
.lcp
= Starting
;
2983 STAT(session_created
);
2988 controlt
*c
= controlnew(14); // CDN
2991 STAT(session_overflow
);
2992 LOG(1, 0, t
, "No free sessions\n");
2993 control16(c
, 1, 4, 0); // temporary lack of resources
2996 control16(c
, 1, 2, 7); // shutting down, try another
2998 controladd(c
, asession
, t
); // send the message
3005 if (amagic
== 0) amagic
= time_now
;
3006 session
[s
].magic
= amagic
; // set magic number
3007 session
[s
].flags
= aflags
; // set flags received
3008 session
[s
].mru
= PPPoE_MRU
; // default
3009 controlnull(t
); // ack
3012 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3013 sess_local
[s
].ppp_mru
= MRU
;
3015 // Set multilink options before sending initial LCP packet
3016 sess_local
[s
].mp_mrru
= 1614;
3017 sess_local
[s
].mp_epdis
= config
->bind_address
? config
->bind_address
: my_address
;
3020 change_state(s
, lcp
, RequestSent
);
3024 controlnull(t
); // ack
3025 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3028 LOG(1, s
, t
, "Missing message type\n");
3031 STAT(tunnel_rx_errors
);
3033 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3035 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3038 if (chapresponse
) free(chapresponse
);
3039 cluster_send_tunnel(t
);
3043 LOG(4, s
, t
, " Got a ZLB ack\n");
3050 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3051 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3052 { // HDLC address header, discard
3058 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3059 STAT(tunnel_rx_errors
);
3069 proto
= ntohs(*(uint16_t *) p
);
3074 if (s
&& !session
[s
].opened
) // Is something wrong??
3076 if (!config
->cluster_iam_master
)
3078 // Pass it off to the master to deal with..
3079 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3084 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3085 STAT(tunnel_rx_errors
);
3089 if (proto
== PPPPAP
)
3091 session
[s
].last_packet
= time_now
;
3092 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3093 processpap(s
, t
, p
, l
);
3095 else if (proto
== PPPCHAP
)
3097 session
[s
].last_packet
= time_now
;
3098 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3099 processchap(s
, t
, p
, l
);
3101 else if (proto
== PPPLCP
)
3103 session
[s
].last_packet
= time_now
;
3104 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3105 processlcp(s
, t
, p
, l
);
3107 else if (proto
== PPPIPCP
)
3109 session
[s
].last_packet
= time_now
;
3110 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3111 processipcp(s
, t
, p
, l
);
3113 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3115 session
[s
].last_packet
= time_now
;
3116 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3117 processipv6cp(s
, t
, p
, l
);
3119 else if (proto
== PPPCCP
)
3121 session
[s
].last_packet
= time_now
;
3122 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3123 processccp(s
, t
, p
, l
);
3125 else if (proto
== PPPIP
)
3129 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3130 return; // closing session, PPP not processed
3133 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3134 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3136 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3140 processipin(s
, t
, p
, l
);
3142 else if (proto
== PPPMP
)
3146 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3147 return; // closing session, PPP not processed
3150 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3151 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3153 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3157 processmpin(s
, t
, p
, l
);
3159 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3163 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3164 return; // closing session, PPP not processed
3167 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3168 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3170 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3174 processipv6in(s
, t
, p
, l
);
3176 else if (session
[s
].ppp
.lcp
== Opened
)
3178 session
[s
].last_packet
= time_now
;
3179 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3180 protoreject(s
, t
, p
, l
, proto
);
3184 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3185 proto
, ppp_state(session
[s
].ppp
.lcp
));
3190 // read and process packet on tun
3191 static void processtun(uint8_t * buf
, int len
)
3193 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3194 STAT(tun_rx_packets
);
3195 INC_STAT(tun_rx_bytes
, len
);
3203 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3204 STAT(tun_rx_errors
);
3208 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3209 processipout(buf
, len
);
3210 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3211 && config
->ipv6_prefix
.s6_addr
[0])
3212 processipv6out(buf
, len
);
3217 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3218 // that we look at the whole of the tunnel, radius and session tables
3220 static void regular_cleanups(double period
)
3222 // Next tunnel, radius and session to check for actions on.
3223 static tunnelidt t
= 0;
3225 static sessionidt s
= 0;
3238 // divide up tables into slices based on the last run
3239 t_slice
= config
->cluster_highest_tunnelid
* period
;
3240 r_slice
= (MAXRADIUS
- 1) * period
;
3241 s_slice
= config
->cluster_highest_sessionid
* period
;
3245 else if (t_slice
> config
->cluster_highest_tunnelid
)
3246 t_slice
= config
->cluster_highest_tunnelid
;
3250 else if (r_slice
> (MAXRADIUS
- 1))
3251 r_slice
= MAXRADIUS
- 1;
3255 else if (s_slice
> config
->cluster_highest_sessionid
)
3256 s_slice
= config
->cluster_highest_sessionid
;
3258 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3260 for (i
= 0; i
< t_slice
; i
++)
3263 if (t
> config
->cluster_highest_tunnelid
)
3266 // check for expired tunnels
3267 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3269 STAT(tunnel_timeout
);
3270 tunnelkill(t
, "Expired");
3274 // check for message resend
3275 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3277 // resend pending messages as timeout on reply
3278 if (tunnel
[t
].retry
<= TIME
)
3280 controlt
*c
= tunnel
[t
].controls
;
3281 uint16_t w
= tunnel
[t
].window
;
3282 tunnel
[t
].try++; // another try
3283 if (tunnel
[t
].try > 5)
3284 tunnelkill(t
, "Timeout on control message"); // game over
3288 tunnelsend(c
->buf
, c
->length
, t
);
3296 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3298 controlt
*c
= controlnew(6); // sending HELLO
3299 controladd(c
, 0, t
); // send the message
3300 LOG(3, 0, t
, "Sending HELLO message\n");
3304 // Check for tunnel changes requested from the CLI
3305 if ((a
= cli_tunnel_actions
[t
].action
))
3307 cli_tunnel_actions
[t
].action
= 0;
3308 if (a
& CLI_TUN_KILL
)
3310 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3311 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3317 for (i
= 0; i
< r_slice
; i
++)
3323 if (!radius
[r
].state
)
3326 if (radius
[r
].retry
<= TIME
)
3333 for (i
= 0; i
< s_slice
; i
++)
3336 if (s
> config
->cluster_highest_sessionid
)
3339 if (!session
[s
].opened
) // Session isn't in use
3342 // check for expired sessions
3345 if (session
[s
].die
<= TIME
)
3347 sessionkill(s
, "Expired");
3354 if (sess_local
[s
].lcp
.restart
<= time_now
)
3356 int next_state
= session
[s
].ppp
.lcp
;
3357 switch (session
[s
].ppp
.lcp
)
3361 next_state
= RequestSent
;
3364 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3366 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3367 sendlcp(s
, session
[s
].tunnel
);
3368 change_state(s
, lcp
, next_state
);
3372 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3373 STAT(session_timeout
);
3383 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3385 int next_state
= session
[s
].ppp
.ipcp
;
3386 switch (session
[s
].ppp
.ipcp
)
3390 next_state
= RequestSent
;
3393 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3395 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3396 sendipcp(s
, session
[s
].tunnel
);
3397 change_state(s
, ipcp
, next_state
);
3401 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3402 STAT(session_timeout
);
3412 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3414 int next_state
= session
[s
].ppp
.ipv6cp
;
3415 switch (session
[s
].ppp
.ipv6cp
)
3419 next_state
= RequestSent
;
3422 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3424 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3425 sendipv6cp(s
, session
[s
].tunnel
);
3426 change_state(s
, ipv6cp
, next_state
);
3430 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3431 change_state(s
, ipv6cp
, Stopped
);
3438 if (sess_local
[s
].ccp
.restart
<= time_now
)
3440 int next_state
= session
[s
].ppp
.ccp
;
3441 switch (session
[s
].ppp
.ccp
)
3445 next_state
= RequestSent
;
3448 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3450 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3451 sendccp(s
, session
[s
].tunnel
);
3452 change_state(s
, ccp
, next_state
);
3456 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3457 change_state(s
, ccp
, Stopped
);
3464 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3465 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3467 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3468 STAT(session_timeout
);
3473 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3474 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3475 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3477 uint8_t b
[MAXETHER
];
3479 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3483 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3484 *(uint16_t *)(q
+ 2) = htons(8); // Length
3485 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3487 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3488 (int)(time_now
- session
[s
].last_packet
));
3489 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3490 sess_local
[s
].last_echo
= time_now
;
3494 // Drop sessions who have reached session_timeout seconds
3495 if (session
[s
].session_timeout
)
3497 bundleidt bid
= session
[s
].bundle
;
3500 if (time_now
- bundle
[bid
].last_check
>= 1)
3502 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3503 bundle
[bid
].last_check
= time_now
;
3504 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3507 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3509 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3516 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3518 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3524 // Drop sessions who have reached idle_timeout seconds
3525 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3527 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3528 STAT(session_timeout
);
3533 // Check for actions requested from the CLI
3534 if ((a
= cli_session_actions
[s
].action
))
3538 cli_session_actions
[s
].action
= 0;
3539 if (a
& CLI_SESS_KILL
)
3541 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3542 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3543 a
= 0; // dead, no need to check for other actions
3547 if (a
& CLI_SESS_NOSNOOP
)
3549 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3550 session
[s
].snoop_ip
= 0;
3551 session
[s
].snoop_port
= 0;
3555 else if (a
& CLI_SESS_SNOOP
)
3557 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3558 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3559 cli_session_actions
[s
].snoop_port
);
3561 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3562 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3567 if (a
& CLI_SESS_NOTHROTTLE
)
3569 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3570 throttle_session(s
, 0, 0);
3574 else if (a
& CLI_SESS_THROTTLE
)
3576 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3577 cli_session_actions
[s
].throttle_in
,
3578 cli_session_actions
[s
].throttle_out
);
3580 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3585 if (a
& CLI_SESS_NOFILTER
)
3587 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3588 filter_session(s
, 0, 0);
3592 else if (a
& CLI_SESS_FILTER
)
3594 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3595 cli_session_actions
[s
].filter_in
,
3596 cli_session_actions
[s
].filter_out
);
3598 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3604 cluster_send_session(s
);
3607 // RADIUS interim accounting
3608 if (config
->radius_accounting
&& config
->radius_interim
> 0
3609 && session
[s
].ip
&& !session
[s
].walled_garden
3610 && !sess_local
[s
].radius
// RADIUS already in progress
3611 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3612 && session
[s
].flags
& SESSION_STARTED
)
3614 int rad
= radiusnew(s
);
3617 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3618 STAT(radius_overflow
);
3622 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3623 session
[s
].user
, session
[s
].unique_id
);
3625 radiussend(rad
, RADIUSINTERIM
);
3626 sess_local
[s
].last_interim
= time_now
;
3631 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3632 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3636 // Are we in the middle of a tunnel update, or radius
3639 static int still_busy(void)
3642 static clockt last_talked
= 0;
3643 static clockt start_busy_wait
= 0;
3645 if (!config
->cluster_iam_master
)
3648 static time_t stopped_bgp
= 0;
3653 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3655 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3656 if (bgp_peers
[i
].state
== Established
)
3657 bgp_stop(&bgp_peers
[i
]);
3659 stopped_bgp
= time_now
;
3661 // we don't want to become master
3662 cluster_send_ping(0);
3667 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
3675 if (main_quit
== QUIT_SHUTDOWN
)
3677 static int dropped
= 0;
3682 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3683 for (i
= 1; i
< MAXTUNNEL
; i
++)
3684 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3685 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3691 if (start_busy_wait
== 0)
3692 start_busy_wait
= TIME
;
3694 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3696 if (!tunnel
[i
].controlc
)
3699 if (last_talked
!= TIME
)
3701 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3707 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3708 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3710 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3714 for (i
= 1; i
< MAXRADIUS
; i
++)
3716 if (radius
[i
].state
== RADIUSNULL
)
3718 if (radius
[i
].state
== RADIUSWAIT
)
3721 if (last_talked
!= TIME
)
3723 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3733 # include <sys/epoll.h>
3735 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3736 # include "fake_epoll.h"
3739 // the base set of fds polled: cli, cluster, tun, udp, control, dae
3742 // additional polled fds
3744 # define EXTRA_FDS BGP_NUM_PEERS
3746 # define EXTRA_FDS 0
3749 // main loop - gets packets on tun or udp and processes them
3750 static void mainloop(void)
3754 clockt next_cluster_ping
= 0; // send initial ping immediately
3755 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3756 int maxevent
= sizeof(events
)/sizeof(*events
);
3758 if ((epollfd
= epoll_create(maxevent
)) < 0)
3760 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3764 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d\n",
3765 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
);
3767 /* setup our fds to poll for input */
3769 static struct event_data d
[BASE_FDS
];
3770 struct epoll_event e
;
3777 d
[i
].type
= FD_TYPE_CLI
;
3778 e
.data
.ptr
= &d
[i
++];
3779 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3782 d
[i
].type
= FD_TYPE_CLUSTER
;
3783 e
.data
.ptr
= &d
[i
++];
3784 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3786 d
[i
].type
= FD_TYPE_TUN
;
3787 e
.data
.ptr
= &d
[i
++];
3788 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3790 d
[i
].type
= FD_TYPE_UDP
;
3791 e
.data
.ptr
= &d
[i
++];
3792 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3794 d
[i
].type
= FD_TYPE_CONTROL
;
3795 e
.data
.ptr
= &d
[i
++];
3796 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3798 d
[i
].type
= FD_TYPE_DAE
;
3799 e
.data
.ptr
= &d
[i
++];
3800 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3804 signal(SIGPIPE
, SIG_IGN
);
3805 bgp_setup(config
->as_number
);
3806 if (config
->bind_address
)
3807 bgp_add_route(config
->bind_address
, 0xffffffff);
3809 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3811 if (config
->neighbour
[i
].name
[0])
3812 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3813 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3814 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3818 while (!main_quit
|| still_busy())
3828 config
->reload_config
++;
3831 if (config
->reload_config
)
3833 config
->reload_config
= 0;
3841 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3842 STAT(select_called
);
3847 if (errno
== EINTR
||
3848 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3851 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3857 struct sockaddr_in addr
;
3858 struct in_addr local
;
3863 int cluster_ready
= 0;
3866 int cluster_pkts
= 0;
3868 uint32_t bgp_events
[BGP_NUM_PEERS
];
3869 memset(bgp_events
, 0, sizeof(bgp_events
));
3872 for (c
= n
, i
= 0; i
< c
; i
++)
3874 struct event_data
*d
= events
[i
].data
.ptr
;
3878 case FD_TYPE_CLI
: // CLI connections
3882 alen
= sizeof(addr
);
3883 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3889 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3895 // these are handled below, with multiple interleaved reads
3896 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3897 case FD_TYPE_TUN
: tun_ready
++; break;
3898 case FD_TYPE_UDP
: udp_ready
++; break;
3900 case FD_TYPE_CONTROL
: // nsctl commands
3901 alen
= sizeof(addr
);
3902 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3903 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3907 case FD_TYPE_DAE
: // DAE requests
3908 alen
= sizeof(addr
);
3909 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3910 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3914 case FD_TYPE_RADIUS
: // RADIUS response
3915 alen
= sizeof(addr
);
3916 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3917 if (s
>= 0 && config
->cluster_iam_master
)
3919 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3920 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3921 processrad(buf
, s
, d
->index
);
3923 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3924 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3932 bgp_events
[d
->index
] = events
[i
].events
;
3938 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3943 bgp_process(bgp_events
);
3946 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3951 alen
= sizeof(addr
);
3952 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3954 processudp(buf
, s
, &addr
);
3967 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3982 alen
= sizeof(addr
);
3983 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3985 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3996 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3997 STAT(multi_read_used
);
3999 if (c
>= config
->multi_read_count
)
4001 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
4002 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
4004 STAT(multi_read_exceeded
);
4011 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4013 // Log current traffic stats
4014 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4015 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4016 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4017 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4018 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4020 udp_tx
= udp_rx
= 0;
4021 udp_rx_pkt
= eth_rx_pkt
= 0;
4022 eth_tx
= eth_rx
= 0;
4025 if (config
->dump_speed
)
4026 printf("%s\n", config
->bandwidth
);
4028 // Update the internal time counter
4029 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4033 struct param_timer p
= { time_now
};
4034 run_plugins(PLUGIN_TIMER
, &p
);
4038 // Runs on every machine (master and slaves).
4039 if (next_cluster_ping
<= TIME
)
4041 // Check to see which of the cluster is still alive..
4043 cluster_send_ping(basetime
); // Only does anything if we're a slave
4044 cluster_check_master(); // ditto.
4046 cluster_heartbeat(); // Only does anything if we're a master.
4047 cluster_check_slaves(); // ditto.
4049 master_update_counts(); // If we're a slave, send our byte counters to our master.
4051 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4052 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4054 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4057 if (!config
->cluster_iam_master
)
4060 // Run token bucket filtering queue..
4061 // Only run it every 1/10th of a second.
4063 static clockt last_run
= 0;
4064 if (last_run
!= TIME
)
4071 // Handle timeouts, retries etc.
4073 static double last_clean
= 0;
4077 TIME
= now(&this_clean
);
4078 diff
= this_clean
- last_clean
;
4080 // Run during idle time (after we've handled
4081 // all incoming packets) or every 1/10th sec
4082 if (!more
|| diff
> 0.1)
4084 regular_cleanups(diff
);
4085 last_clean
= this_clean
;
4089 if (*config
->accounting_dir
)
4091 static clockt next_acct
= 0;
4092 static clockt next_shut_acct
= 0;
4094 if (next_acct
<= TIME
)
4096 // Dump accounting data
4097 next_acct
= TIME
+ ACCT_TIME
;
4098 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4101 else if (next_shut_acct
<= TIME
)
4103 // Dump accounting data for shutdown sessions
4104 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4111 // Are we the master and shutting down??
4112 if (config
->cluster_iam_master
)
4113 cluster_heartbeat(); // Flush any queued changes..
4115 // Ok. Notify everyone we're shutting down. If we're
4116 // the master, this will force an election.
4117 cluster_send_ping(0);
4120 // Important!!! We MUST not process any packets past this point!
4121 LOG(1, 0, 0, "Shutdown complete\n");
4124 static void stripdomain(char *host
)
4128 if ((p
= strchr(host
, '.')))
4134 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4140 while (fgets(buf
, sizeof(buf
), resolv
))
4142 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4145 if (!isspace(buf
[6]))
4149 while (isspace(*b
)) b
++;
4154 while (*b
&& !isspace(*b
)) b
++;
4156 if (buf
[0] == 'd') // domain is canonical
4162 // first search line
4165 // hold, may be subsequent domain line
4166 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4177 int hl
= strlen(host
);
4178 int dl
= strlen(domain
);
4179 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4180 host
[hl
-dl
- 1] = 0;
4184 *p
= 0; // everything after first dot
4189 // Init data structures
4190 static void initdata(int optdebug
, char *optconfig
)
4194 if (!(config
= shared_malloc(sizeof(configt
))))
4196 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4200 memset(config
, 0, sizeof(configt
));
4201 time(&config
->start_time
);
4202 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4203 config
->debug
= optdebug
;
4204 config
->num_tbfs
= MAXTBFS
;
4205 config
->rl_rate
= 28; // 28kbps
4206 config
->cluster_mcast_ttl
= 1;
4207 config
->cluster_master_min_adv
= 1;
4208 config
->ppp_restart_time
= 3;
4209 config
->ppp_max_configure
= 10;
4210 config
->ppp_max_failure
= 5;
4211 config
->kill_timedout_sessions
= 1;
4212 strcpy(config
->random_device
, RANDOMDEVICE
);
4214 log_stream
= stderr
;
4217 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4219 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4222 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4225 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4227 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4230 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4232 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4235 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4237 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4240 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4242 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4245 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4247 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4251 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4253 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4257 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4259 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4263 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4265 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4269 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4271 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4274 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4276 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4278 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4281 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4283 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4285 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4288 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4290 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4291 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4292 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4293 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4294 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4296 // Put all the sessions on the free list marked as undefined.
4297 for (i
= 1; i
< MAXSESSION
; i
++)
4299 session
[i
].next
= i
+ 1;
4300 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4302 session
[MAXSESSION
- 1].next
= 0;
4305 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4306 for (i
= 1; i
< MAXTUNNEL
; i
++)
4307 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4309 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4310 bundle
[i
].state
= BUNDLEUNDEF
;
4315 // Grab my hostname unless it's been specified
4316 gethostname(hostname
, sizeof(hostname
));
4317 stripdomain(hostname
);
4320 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4323 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4325 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4331 static int assign_ip_address(sessionidt s
)
4335 time_t best_time
= time_now
;
4336 char *u
= session
[s
].user
;
4340 CSTAT(assign_ip_address
);
4342 for (i
= 1; i
< ip_pool_size
; i
++)
4344 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4347 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4354 if (ip_address_pool
[i
].last
< best_time
)
4357 if (!(best_time
= ip_address_pool
[i
].last
))
4358 break; // never used, grab this one
4364 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4368 session
[s
].ip
= ip_address_pool
[best
].address
;
4369 session
[s
].ip_pool_index
= best
;
4370 ip_address_pool
[best
].assigned
= 1;
4371 ip_address_pool
[best
].last
= time_now
;
4372 ip_address_pool
[best
].session
= s
;
4373 if (session
[s
].walled_garden
)
4374 /* Don't track addresses of users in walled garden (note: this
4375 means that their address isn't "sticky" even if they get
4377 ip_address_pool
[best
].user
[0] = 0;
4379 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4382 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4383 reuse
? "Reusing" : "Allocating", best
);
4388 static void free_ip_address(sessionidt s
)
4390 int i
= session
[s
].ip_pool_index
;
4393 CSTAT(free_ip_address
);
4396 return; // what the?
4398 if (i
< 0) // Is this actually part of the ip pool?
4402 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4404 ip_address_pool
[i
].assigned
= 0;
4405 ip_address_pool
[i
].session
= 0;
4406 ip_address_pool
[i
].last
= time_now
;
4410 // Fsck the address pool against the session table.
4411 // Normally only called when we become a master.
4413 // This isn't perfect: We aren't keep tracking of which
4414 // users used to have an IP address.
4416 void rebuild_address_pool(void)
4421 // Zero the IP pool allocation, and build
4422 // a map from IP address to pool index.
4423 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4425 ip_address_pool
[i
].assigned
= 0;
4426 ip_address_pool
[i
].session
= 0;
4427 if (!ip_address_pool
[i
].address
)
4430 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4433 for (i
= 0; i
< MAXSESSION
; ++i
)
4436 if (!(session
[i
].opened
&& session
[i
].ip
))
4439 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4441 if (session
[i
].ip_pool_index
< 0)
4443 // Not allocated out of the pool.
4444 if (ipid
< 1) // Not found in the pool either? good.
4447 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4448 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4450 // Fall through and process it as part of the pool.
4454 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4456 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4458 session
[i
].ip_pool_index
= ipid
;
4462 ip_address_pool
[ipid
].assigned
= 1;
4463 ip_address_pool
[ipid
].session
= i
;
4464 ip_address_pool
[ipid
].last
= time_now
;
4465 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4466 session
[i
].ip_pool_index
= ipid
;
4467 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4472 // Fix the address pool to match a changed session.
4473 // (usually when the master sends us an update).
4474 static void fix_address_pool(int sid
)
4478 ipid
= session
[sid
].ip_pool_index
;
4480 if (ipid
> ip_pool_size
)
4481 return; // Ignore it. rebuild_address_pool will fix it up.
4483 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4484 return; // Just ignore it. rebuild_address_pool will take care of it.
4486 ip_address_pool
[ipid
].assigned
= 1;
4487 ip_address_pool
[ipid
].session
= sid
;
4488 ip_address_pool
[ipid
].last
= time_now
;
4489 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4493 // Add a block of addresses to the IP pool to hand out.
4495 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
4499 mask
= 0xffffffff; // Host route only.
4503 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4506 for (i
= addr
;(i
& mask
) == addr
; ++i
)
4508 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4509 continue; // Skip 0 and broadcast addresses.
4511 ip_address_pool
[ip_pool_size
].address
= i
;
4512 ip_address_pool
[ip_pool_size
].assigned
= 0;
4514 if (ip_pool_size
>= MAXIPPOOL
)
4516 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4522 // Initialize the IP address pool
4523 static void initippool()
4528 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4530 if (!(f
= fopen(IPPOOLFILE
, "r")))
4532 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4536 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4539 buf
[4095] = 0; // Force it to be zero terminated/
4541 if (*buf
== '#' || *buf
== '\n')
4542 continue; // Skip comments / blank lines
4543 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4544 if ((p
= (char *)strchr(buf
, ':')))
4548 src
= inet_addr(buf
);
4549 if (src
== INADDR_NONE
)
4551 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4554 // This entry is for a specific IP only
4555 if (src
!= config
->bind_address
)
4560 if ((p
= (char *)strchr(pool
, '/')))
4564 in_addr_t start
= 0, mask
= 0;
4566 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4568 if (!*p
|| !(numbits
= atoi(p
)))
4570 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4573 start
= ntohl(inet_addr(pool
));
4574 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
4576 // Add a static route for this pool
4577 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
4578 fmtaddr(htonl(start
), 0), 32 + mask
);
4580 routeset(0, start
, mask
, 0, 1);
4582 add_to_ip_pool(start
, mask
);
4586 // It's a single ip address
4587 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4591 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4594 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4596 struct sockaddr_in snoop_addr
= {0};
4597 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4600 snoop_addr
.sin_family
= AF_INET
;
4601 snoop_addr
.sin_addr
.s_addr
= destination
;
4602 snoop_addr
.sin_port
= ntohs(port
);
4604 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4605 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4606 htons(snoop_addr
.sin_port
));
4608 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4609 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4611 STAT(packets_snooped
);
4614 static int dump_session(FILE **f
, sessiont
*s
)
4616 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4621 char filename
[1024];
4623 time_t now
= time(NULL
);
4625 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4626 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4628 if (!(*f
= fopen(filename
, "w")))
4630 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4634 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4635 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4640 "# format: username ip qos uptxoctets downrxoctets\n",
4642 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4647 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4648 fprintf(*f
, "%s %s %d %u %u\n",
4649 s
->user
, // username
4650 fmtaddr(htonl(s
->ip
), 0), // ip
4651 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4652 (uint32_t) s
->cin_delta
, // uptxoctets
4653 (uint32_t) s
->cout_delta
); // downrxoctets
4655 s
->cin_delta
= s
->cout_delta
= 0;
4660 static void dump_acct_info(int all
)
4666 CSTAT(dump_acct_info
);
4670 for (i
= 0; i
< shut_acct_n
; i
++)
4671 dump_session(&f
, &shut_acct
[i
]);
4677 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4678 dump_session(&f
, &session
[i
]);
4685 int main(int argc
, char *argv
[])
4689 char *optconfig
= CONFIGFILE
;
4691 time(&basetime
); // start clock
4694 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4699 if (fork()) exit(0);
4701 freopen("/dev/null", "r", stdin
);
4702 freopen("/dev/null", "w", stdout
);
4703 freopen("/dev/null", "w", stderr
);
4712 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4715 printf("Args are:\n"
4716 "\t-d\t\tDetach from terminal\n"
4717 "\t-c <file>\tConfig file\n"
4718 "\t-h <hostname>\tForce hostname\n"
4726 // Start the timer routine off
4728 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4731 initdata(optdebug
, optconfig
);
4736 init_tbf(config
->num_tbfs
);
4738 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4739 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4740 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4743 rlim
.rlim_cur
= RLIM_INFINITY
;
4744 rlim
.rlim_max
= RLIM_INFINITY
;
4745 // Remove the maximum core size
4746 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4747 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4749 // Make core dumps go to /tmp
4753 if (config
->scheduler_fifo
)
4756 struct sched_param params
= {0};
4757 params
.sched_priority
= 1;
4759 if (get_nprocs() < 2)
4761 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4762 config
->scheduler_fifo
= 0;
4766 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4768 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4772 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4773 config
->scheduler_fifo
= 0;
4780 /* Set up the cluster communications port. */
4781 if (cluster_init() < 0)
4785 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4793 unsigned seed
= time_now
^ getpid();
4794 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4798 signal(SIGHUP
, sighup_handler
);
4799 signal(SIGCHLD
, sigchild_handler
);
4800 signal(SIGTERM
, shutdown_handler
);
4801 signal(SIGINT
, shutdown_handler
);
4802 signal(SIGQUIT
, shutdown_handler
);
4804 // Prevent us from getting paged out
4805 if (config
->lock_pages
)
4807 if (!mlockall(MCL_CURRENT
))
4808 LOG(1, 0, 0, "Locking pages into memory\n");
4810 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4815 /* remove plugins (so cleanup code gets run) */
4818 // Remove the PID file if we wrote it
4819 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4820 unlink(config
->pid_file
);
4822 /* kill CLI children */
4823 signal(SIGTERM
, SIG_IGN
);
4828 static void sighup_handler(int sig
)
4833 static void shutdown_handler(int sig
)
4835 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4838 static void sigchild_handler(int sig
)
4840 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4844 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4847 *challenge_response
= NULL
;
4849 if (!*config
->l2tp_secret
)
4851 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4855 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4857 *challenge_response
= calloc(17, 1);
4860 MD5_Update(&ctx
, &id
, 1);
4861 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4862 MD5_Update(&ctx
, challenge
, challenge_length
);
4863 MD5_Final(*challenge_response
, &ctx
);
4868 static int facility_value(char *name
)
4871 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4873 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4874 return facilitynames
[i
].c_val
;
4879 static void update_config()
4883 static int timeout
= 0;
4884 static int interval
= 0;
4891 if (log_stream
!= stderr
)
4897 if (*config
->log_filename
)
4899 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4901 char *p
= config
->log_filename
+ 7;
4904 openlog("l2tpns", LOG_PID
, facility_value(p
));
4908 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4910 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4912 fseek(log_stream
, 0, SEEK_END
);
4913 setbuf(log_stream
, NULL
);
4917 log_stream
= stderr
;
4918 setbuf(log_stream
, NULL
);
4924 log_stream
= stderr
;
4925 setbuf(log_stream
, NULL
);
4928 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4929 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4931 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4932 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4933 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4935 // reset MRU/MSS globals
4936 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4937 if (MRU
> PPPoE_MRU
)
4940 MSS
= MRU
- TCP_HDRS
;
4943 config
->numradiusservers
= 0;
4944 for (i
= 0; i
< MAXRADSERVER
; i
++)
4945 if (config
->radiusserver
[i
])
4947 config
->numradiusservers
++;
4948 // Set radius port: if not set, take the port from the
4949 // first radius server. For the first radius server,
4950 // take the #defined default value from l2tpns.h
4952 // test twice, In case someone works with
4953 // a secondary radius server without defining
4954 // a primary one, this will work even then.
4955 if (i
> 0 && !config
->radiusport
[i
])
4956 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4957 if (!config
->radiusport
[i
])
4958 config
->radiusport
[i
] = RADPORT
;
4961 if (!config
->numradiusservers
)
4962 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4964 // parse radius_authtypes_s
4965 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4966 p
= config
->radius_authtypes_s
;
4969 char *s
= strpbrk(p
, " \t,");
4975 while (*s
== ' ' || *s
== '\t')
4982 if (!strncasecmp("chap", p
, strlen(p
)))
4984 else if (!strncasecmp("pap", p
, strlen(p
)))
4987 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4989 config
->radius_authtypes
|= type
;
4990 if (!config
->radius_authprefer
)
4991 config
->radius_authprefer
= type
;
4996 if (!config
->radius_authtypes
)
4998 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4999 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5002 // normalise radius_authtypes_s
5003 if (config
->radius_authprefer
== AUTHPAP
)
5005 strcpy(config
->radius_authtypes_s
, "pap");
5006 if (config
->radius_authtypes
& AUTHCHAP
)
5007 strcat(config
->radius_authtypes_s
, ", chap");
5011 strcpy(config
->radius_authtypes_s
, "chap");
5012 if (config
->radius_authtypes
& AUTHPAP
)
5013 strcat(config
->radius_authtypes_s
, ", pap");
5016 if (!config
->radius_dae_port
)
5017 config
->radius_dae_port
= DAEPORT
;
5019 // re-initialise the random number source
5020 initrandom(config
->random_device
);
5023 for (i
= 0; i
< MAXPLUGINS
; i
++)
5025 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5028 if (*config
->plugins
[i
])
5031 add_plugin(config
->plugins
[i
]);
5033 else if (*config
->old_plugins
[i
])
5036 remove_plugin(config
->old_plugins
[i
]);
5041 guest_accounts_num
= 0;
5042 char *p2
= config
->guest_user
;
5045 char *s
= strpbrk(p2
, " \t,");
5049 while (*s
== ' ' || *s
== '\t')
5056 strcpy(guest_users
[guest_accounts_num
], p2
);
5057 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5058 guest_accounts_num
++;
5061 // Rebuild the guest_user array
5062 strcpy(config
->guest_user
, "");
5064 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5066 strcat(config
->guest_user
, guest_users
[ui
]);
5067 if (ui
<guest_accounts_num
-1)
5069 strcat(config
->guest_user
, ",");
5074 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5075 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5076 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5077 if (!*config
->cluster_interface
)
5078 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5080 if (!config
->cluster_hb_interval
)
5081 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5083 if (!config
->cluster_hb_timeout
)
5084 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5086 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5088 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5089 // late, ensure we're sufficiently larger than that
5090 int t
= 4 * config
->cluster_hb_interval
+ 11;
5092 if (config
->cluster_hb_timeout
< t
)
5094 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5095 config
->cluster_hb_timeout
= t
;
5098 // Push timing changes to the slaves immediately if we're the master
5099 if (config
->cluster_iam_master
)
5100 cluster_heartbeat();
5102 interval
= config
->cluster_hb_interval
;
5103 timeout
= config
->cluster_hb_timeout
;
5107 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5110 if ((f
= fopen(config
->pid_file
, "w")))
5112 fprintf(f
, "%d\n", getpid());
5114 config
->wrote_pid
= 1;
5118 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5123 static void read_config_file()
5127 if (!config
->config_file
) return;
5128 if (!(f
= fopen(config
->config_file
, "r")))
5130 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5134 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5136 LOG(3, 0, 0, "Done reading config file\n");
5140 int sessionsetup(sessionidt s
, tunnelidt t
)
5142 // A session now exists, set it up
5148 CSTAT(sessionsetup
);
5150 LOG(3, s
, t
, "Doing session setup for session\n");
5152 // Join a bundle if the MRRU option is accepted
5153 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5155 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5156 if (join_bundle(s
) > 0)
5157 cluster_send_bundle(session
[s
].bundle
);
5160 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5161 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5168 assign_ip_address(s
);
5171 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5172 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5175 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5176 fmtaddr(htonl(session
[s
].ip
), 0));
5180 // Make sure this is right
5181 session
[s
].tunnel
= t
;
5183 // zap old sessions with same IP and/or username
5184 // Don't kill gardened sessions - doing so leads to a DoS
5185 // from someone who doesn't need to know the password
5188 user
= session
[s
].user
;
5189 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5191 if (i
== s
) continue;
5192 if (!session
[s
].opened
) continue;
5193 // Allow duplicate sessions for multilink ones of the same bundle.
5194 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5196 if (ip
== session
[i
].ip
)
5198 sessionkill(i
, "Duplicate IP address");
5202 if (config
->allow_duplicate_users
) continue;
5203 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5207 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5209 if (!strcasecmp(user
, guest_users
[gu
]))
5215 if (found
) continue;
5217 // Drop the new session in case of duplicate sessionss, not the old one.
5218 if (!strcasecmp(user
, session
[i
].user
))
5219 sessionkill(i
, "Duplicate session for users");
5223 // no need to set a route for the same IP address of the bundle
5224 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5228 // Add the route for this session.
5229 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5231 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
5232 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
5235 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
5238 // Static IPs need to be routed if not already
5239 // convered by a Framed-Route. Anything else is part
5240 // of the IP address pool and is already routed, it
5241 // just needs to be added to the IP cache.
5242 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5243 if (session
[s
].ip_pool_index
== -1) // static ip
5245 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5248 cache_ipmap(session
[s
].ip
, s
);
5251 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5252 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5254 // Run the plugin's against this new session.
5256 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5257 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5260 // Allocate TBFs if throttled
5261 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5262 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5264 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5266 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5267 fmtaddr(htonl(session
[s
].ip
), 0),
5268 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5270 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5272 return 1; // RADIUS OK and IP allocated, done...
5276 // This session just got dropped on us by the master or something.
5277 // Make sure our tables up up to date...
5279 int load_session(sessionidt s
, sessiont
*new)
5285 if (new->ip_pool_index
>= MAXIPPOOL
||
5286 new->tunnel
>= MAXTUNNEL
)
5288 LOG(0, s
, 0, "Strange session update received!\n");
5289 // FIXME! What to do here?
5294 // Ok. All sanity checks passed. Now we're committed to
5295 // loading the new session.
5298 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5300 // See if routes/ip cache need updating
5301 if (new->ip
!= session
[s
].ip
)
5304 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5305 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5306 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
5314 // remove old routes...
5315 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5317 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
5318 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
5321 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
5327 if (session
[s
].ip_pool_index
== -1) // static IP
5329 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5331 else // It's part of the IP pool, remove it manually.
5332 uncache_ipmap(session
[s
].ip
);
5337 // add new routes...
5338 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5340 if ((new->ip
& new->route
[i
].mask
) ==
5341 (new->route
[i
].ip
& new->route
[i
].mask
))
5344 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
5350 // If there's a new one, add it.
5351 if (new->ip_pool_index
== -1)
5353 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5356 cache_ipmap(new->ip
, s
);
5361 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5362 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5365 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5367 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5371 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5373 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5374 new->filter_out
= 0;
5377 if (new->filter_in
!= session
[s
].filter_in
)
5379 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5380 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5383 if (new->filter_out
!= session
[s
].filter_out
)
5385 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5386 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5389 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5390 // for walking the sessions to forward byte counts to the master.
5391 config
->cluster_highest_sessionid
= s
;
5393 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5395 // Do fixups into address pool.
5396 if (new->ip_pool_index
!= -1)
5397 fix_address_pool(s
);
5402 static void initplugins()
5406 loaded_plugins
= ll_init();
5407 // Initialize the plugins to nothing
5408 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5409 plugins
[i
] = ll_init();
5412 static void *open_plugin(char *plugin_name
, int load
)
5414 char path
[256] = "";
5416 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5417 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5418 return dlopen(path
, RTLD_NOW
);
5421 // plugin callback to get a config value
5422 static void *getconfig(char *key
, enum config_typet type
)
5426 for (i
= 0; config_values
[i
].key
; i
++)
5428 if (!strcmp(config_values
[i
].key
, key
))
5430 if (config_values
[i
].type
== type
)
5431 return ((void *) config
) + config_values
[i
].offset
;
5433 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5434 key
, type
, config_values
[i
].type
);
5440 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5444 static int add_plugin(char *plugin_name
)
5446 static struct pluginfuncs funcs
= {
5451 sessiontbysessionidt
,
5452 sessionidtbysessiont
,
5459 cluster_send_session
,
5462 void *p
= open_plugin(plugin_name
, 1);
5463 int (*initfunc
)(struct pluginfuncs
*);
5468 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5472 if (ll_contains(loaded_plugins
, p
))
5475 return 0; // already loaded
5479 int *v
= dlsym(p
, "plugin_api_version");
5480 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5482 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5488 if ((initfunc
= dlsym(p
, "plugin_init")))
5490 if (!initfunc(&funcs
))
5492 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5498 ll_push(loaded_plugins
, p
);
5500 for (i
= 0; i
< max_plugin_functions
; i
++)
5503 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5505 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5506 ll_push(plugins
[i
], x
);
5510 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5514 static void run_plugin_done(void *plugin
)
5516 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5522 static int remove_plugin(char *plugin_name
)
5524 void *p
= open_plugin(plugin_name
, 0);
5530 if (ll_contains(loaded_plugins
, p
))
5533 for (i
= 0; i
< max_plugin_functions
; i
++)
5536 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5537 ll_delete(plugins
[i
], x
);
5540 ll_delete(loaded_plugins
, p
);
5546 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5550 int run_plugins(int plugin_type
, void *data
)
5552 int (*func
)(void *data
);
5554 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5555 return PLUGIN_RET_ERROR
;
5557 ll_reset(plugins
[plugin_type
]);
5558 while ((func
= ll_next(plugins
[plugin_type
])))
5562 if (r
!= PLUGIN_RET_OK
)
5563 return r
; // stop here
5566 return PLUGIN_RET_OK
;
5569 static void plugins_done()
5573 ll_reset(loaded_plugins
);
5574 while ((p
= ll_next(loaded_plugins
)))
5578 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5580 struct nsctl request
;
5581 struct nsctl response
;
5582 int type
= unpack_control(&request
, buf
, len
);
5586 if (log_stream
&& config
->debug
>= 4)
5590 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5591 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5595 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5596 dump_control(&request
, log_stream
);
5602 case NSCTL_REQ_LOAD
:
5603 if (request
.argc
!= 1)
5605 response
.type
= NSCTL_RES_ERR
;
5607 response
.argv
[0] = "name of plugin required";
5609 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5611 response
.type
= NSCTL_RES_ERR
;
5613 response
.argv
[0] = !r
5614 ? "plugin already loaded"
5615 : "error loading plugin";
5619 response
.type
= NSCTL_RES_OK
;
5625 case NSCTL_REQ_UNLOAD
:
5626 if (request
.argc
!= 1)
5628 response
.type
= NSCTL_RES_ERR
;
5630 response
.argv
[0] = "name of plugin required";
5632 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5634 response
.type
= NSCTL_RES_ERR
;
5636 response
.argv
[0] = !r
5637 ? "plugin not loaded"
5638 : "plugin not found";
5642 response
.type
= NSCTL_RES_OK
;
5648 case NSCTL_REQ_HELP
:
5649 response
.type
= NSCTL_RES_OK
;
5652 ll_reset(loaded_plugins
);
5653 while ((p
= ll_next(loaded_plugins
)))
5655 char **help
= dlsym(p
, "plugin_control_help");
5656 while (response
.argc
< 0xff && help
&& *help
)
5657 response
.argv
[response
.argc
++] = *help
++;
5662 case NSCTL_REQ_CONTROL
:
5664 struct param_control param
= {
5665 config
->cluster_iam_master
,
5672 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5674 if (r
== PLUGIN_RET_ERROR
)
5676 response
.type
= NSCTL_RES_ERR
;
5678 response
.argv
[0] = param
.additional
5680 : "error returned by plugin";
5682 else if (r
== PLUGIN_RET_NOTMASTER
)
5684 static char msg
[] = "must be run on master: 000.000.000.000";
5686 response
.type
= NSCTL_RES_ERR
;
5688 if (config
->cluster_master_address
)
5690 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5691 response
.argv
[0] = msg
;
5695 response
.argv
[0] = "must be run on master: none elected";
5698 else if (!(param
.response
& NSCTL_RESPONSE
))
5700 response
.type
= NSCTL_RES_ERR
;
5702 response
.argv
[0] = param
.response
5703 ? "unrecognised response value from plugin"
5704 : "unhandled action";
5708 response
.type
= param
.response
;
5710 if (param
.additional
)
5713 response
.argv
[0] = param
.additional
;
5721 response
.type
= NSCTL_RES_ERR
;
5723 response
.argv
[0] = "error unpacking control packet";
5726 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5729 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5733 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5736 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5737 if (log_stream
&& config
->debug
>= 4)
5739 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5740 dump_control(&response
, log_stream
);
5744 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5745 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5750 static tunnelidt
new_tunnel()
5753 for (i
= 1; i
< MAXTUNNEL
; i
++)
5755 if (tunnel
[i
].state
== TUNNELFREE
)
5757 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5758 if (i
> config
->cluster_highest_tunnelid
)
5759 config
->cluster_highest_tunnelid
= i
;
5763 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5768 // We're becoming the master. Do any required setup..
5770 // This is principally telling all the plugins that we're
5771 // now a master, and telling them about all the sessions
5772 // that are active too..
5774 void become_master(void)
5777 static struct event_data d
[RADIUS_FDS
];
5778 struct epoll_event e
;
5780 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5782 // running a bunch of iptables commands is slow and can cause
5783 // the master to drop tunnels on takeover--kludge around the
5784 // problem by forking for the moment (note: race)
5785 if (!fork_and_close())
5787 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5789 if (!session
[s
].opened
) // Not an in-use session.
5792 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5799 for (i
= 0; i
< RADIUS_FDS
; i
++)
5801 d
[i
].type
= FD_TYPE_RADIUS
;
5805 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5809 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5815 if (CLI_HELP_REQUESTED
)
5816 return CLI_HELP_NO_ARGS
;
5819 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5821 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5824 if (!session
[s
].opened
)
5827 idle
= time_now
- session
[s
].last_data
;
5828 idle
/= 5 ; // In multiples of 5 seconds.
5838 for (i
= 0; i
< 63; ++i
)
5840 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5842 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5843 cli_print(cli
, "%d total sessions open.", count
);
5847 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5853 if (CLI_HELP_REQUESTED
)
5854 return CLI_HELP_NO_ARGS
;
5857 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5859 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5862 if (!session
[s
].opened
)
5865 d
= time_now
- session
[s
].opened
;
5868 while (d
> 1 && open
< 32)
5878 for (i
= 0; i
< 30; ++i
)
5880 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5883 cli_print(cli
, "%d total sessions open.", count
);
5889 * This unencodes the AVP using the L2TP secret and the previously
5890 * stored random vector. It overwrites the hidden data with the
5891 * unhidden AVP subformat.
5893 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5899 uint16_t m
= htons(type
);
5901 // Compute initial pad
5903 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5904 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5905 MD5_Update(&ctx
, vector
, vec_len
);
5906 MD5_Final(digest
, &ctx
);
5908 // pointer to last decoded 16 octets
5913 // calculate a new pad based on the last decoded block
5914 if (d
>= sizeof(digest
))
5917 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5918 MD5_Update(&ctx
, last
, sizeof(digest
));
5919 MD5_Final(digest
, &ctx
);
5925 *value
++ ^= digest
[d
++];
5930 int find_filter(char const *name
, size_t len
)
5935 for (i
= 0; i
< MAXFILTER
; i
++)
5937 if (!*ip_filters
[i
].name
)
5945 if (strlen(ip_filters
[i
].name
) != len
)
5948 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5955 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5959 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5960 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5961 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5962 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5963 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5969 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5973 case FILTER_FLAG_OP_ANY
:
5974 return (flags
& sflags
) || (~flags
& cflags
);
5976 case FILTER_FLAG_OP_ALL
:
5977 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5979 case FILTER_FLAG_OP_EST
:
5980 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5986 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5988 uint16_t frag_offset
;
5992 uint16_t src_port
= 0;
5993 uint16_t dst_port
= 0;
5995 ip_filter_rulet
*rule
;
5997 if (len
< 20) // up to end of destination address
6000 if ((*buf
>> 4) != 4) // IPv4
6003 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6005 src_ip
= *(in_addr_t
*) (buf
+ 12);
6006 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6008 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6010 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6011 if (len
< l
+ 4) // ports
6014 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6015 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6016 if (proto
== IPPROTO_TCP
)
6018 if (len
< l
+ 14) // flags
6021 flags
= buf
[l
+ 13] & 0x3f;
6025 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6027 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6030 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6031 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6034 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6035 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6040 // layer 4 deny rules are skipped
6041 if (rule
->action
== FILTER_ACTION_DENY
&&
6042 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6050 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6052 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6055 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6058 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6059 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6066 return rule
->action
== FILTER_ACTION_PERMIT
;