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.169 2006/07/01 12:40:17 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>
48 #include "constants.h"
58 configt
*config
= NULL
; // all configuration
59 int tunfd
= -1; // tun interface file handle. (network device)
60 int udpfd
= -1; // UDP file handle
61 int controlfd
= -1; // Control signal handle
62 int clifd
= -1; // Socket listening for CLI connections.
63 int daefd
= -1; // Socket listening for DAE connections.
64 int snoopfd
= -1; // UDP file handle for sending out intercept data
65 int *radfds
= NULL
; // RADIUS requests file handles
66 int ifrfd
= -1; // File descriptor for routing, etc
67 int ifr6fd
= -1; // File descriptor for IPv6 routing, etc
68 int rand_fd
= -1; // Random data source
69 int cluster_sockfd
= -1; // Intra-cluster communications socket.
70 int epollfd
= -1; // event polling
71 time_t basetime
= 0; // base clock
72 char hostname
[1000] = ""; // us.
73 static int tunidx
; // ifr_ifindex of tun device
74 static int syslog_log
= 0; // are we logging to syslog
75 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
76 uint32_t last_id
= 0; // Unique ID for radius accounting
78 // calculated from config->l2tp_mtu
79 uint16_t MRU
= 0; // PPP MRU
80 uint16_t MSS
= 0; // TCP MSS
82 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
83 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
85 static void *ip_hash
[256]; // Mapping from IP address to session structures.
88 struct ipv6radix
*branch
;
89 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
92 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
93 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
96 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
97 time_t time_now
= 0; // Current time in seconds since epoch.
98 static char time_now_string
[64] = {0}; // Current time as a string.
99 static int time_changed
= 0; // time_now changed
100 char main_quit
= 0; // True if we're in the process of exiting.
101 static char main_reload
= 0; // Re-load pending
102 linked_list
*loaded_plugins
;
103 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
105 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
106 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
108 config_descriptt config_values
[] = {
109 CONFIG("debug", debug
, INT
),
110 CONFIG("log_file", log_filename
, STRING
),
111 CONFIG("pid_file", pid_file
, STRING
),
112 CONFIG("random_device", random_device
, STRING
),
113 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
114 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
115 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
116 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
117 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
118 CONFIG("primary_dns", default_dns1
, IPv4
),
119 CONFIG("secondary_dns", default_dns2
, IPv4
),
120 CONFIG("primary_radius", radiusserver
[0], IPv4
),
121 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
122 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
123 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
124 CONFIG("radius_accounting", radius_accounting
, BOOL
),
125 CONFIG("radius_interim", radius_interim
, INT
),
126 CONFIG("radius_secret", radiussecret
, STRING
),
127 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
128 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
129 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
130 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
131 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
132 CONFIG("guest_account", guest_user
, STRING
),
133 CONFIG("bind_address", bind_address
, IPv4
),
134 CONFIG("peer_address", peer_address
, IPv4
),
135 CONFIG("send_garp", send_garp
, BOOL
),
136 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
137 CONFIG("throttle_buckets", num_tbfs
, INT
),
138 CONFIG("accounting_dir", accounting_dir
, STRING
),
139 CONFIG("dump_speed", dump_speed
, BOOL
),
140 CONFIG("multi_read_count", multi_read_count
, INT
),
141 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
142 CONFIG("lock_pages", lock_pages
, BOOL
),
143 CONFIG("icmp_rate", icmp_rate
, INT
),
144 CONFIG("packet_limit", max_packets
, INT
),
145 CONFIG("cluster_address", cluster_address
, IPv4
),
146 CONFIG("cluster_interface", cluster_interface
, STRING
),
147 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
148 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
149 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
150 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
151 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
155 static char *plugin_functions
[] = {
162 "plugin_new_session",
163 "plugin_kill_session",
165 "plugin_radius_response",
166 "plugin_radius_reset",
167 "plugin_radius_account",
168 "plugin_become_master",
169 "plugin_new_session_master",
172 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
174 // Counters for shutdown sessions
175 static sessiont shut_acct
[8192];
176 static sessionidt shut_acct_n
= 0;
178 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
179 bundlet
*bundle
= NULL
; // Array of bundle structures.
180 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
181 sessiont
*session
= NULL
; // Array of session structures.
182 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
183 radiust
*radius
= NULL
; // Array of radius structures.
184 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
185 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
186 static controlt
*controlfree
= 0;
187 struct Tstats
*_statistics
= NULL
;
189 struct Tringbuffer
*ringbuffer
= NULL
;
192 static void cache_ipmap(in_addr_t ip
, int s
);
193 static void uncache_ipmap(in_addr_t ip
);
194 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, int s
);
195 static void free_ip_address(sessionidt s
);
196 static void dump_acct_info(int all
);
197 static void sighup_handler(int sig
);
198 static void shutdown_handler(int sig
);
199 static void sigchild_handler(int sig
);
200 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
201 static void update_config(void);
202 static void read_config_file(void);
203 static void initplugins(void);
204 static int add_plugin(char *plugin_name
);
205 static int remove_plugin(char *plugin_name
);
206 static void plugins_done(void);
207 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
208 static tunnelidt
new_tunnel(void);
209 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
210 static void bundleclear(bundleidt b
);
212 // on slaves, alow BGP to withdraw cleanly before exiting
215 // quit actions (master)
216 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
217 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
219 // return internal time (10ths since process startup), set f if given
220 // as a side-effect sets time_now, and time_changed
221 static clockt
now(double *f
)
225 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
226 if (t
.tv_sec
!= time_now
)
231 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
234 // work out a retry time based on try number
235 // This is a straight bounded exponential backoff.
236 // Maximum re-try time is 32 seconds. (2^5).
237 clockt
backoff(uint8_t try)
239 if (try > 5) try = 5; // max backoff
240 return now(NULL
) + 10 * (1 << try);
245 // Log a debug message. Typically called via the LOG macro
247 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
249 static char message
[65536] = {0};
255 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
256 ringbuffer
->tail
= 0;
257 if (ringbuffer
->tail
== ringbuffer
->head
)
258 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
259 ringbuffer
->head
= 0;
261 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
262 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
263 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
264 va_start(ap
, format
);
265 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
270 if (config
->debug
< level
) return;
272 va_start(ap
, format
);
273 vsnprintf(message
, sizeof(message
), format
, ap
);
276 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
278 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
283 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
286 const uint8_t *d
= data
;
288 if (config
->debug
< level
) return;
290 // No support for _log_hex to syslog
293 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
294 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
296 for (i
= 0; i
< maxsize
; )
298 fprintf(log_stream
, "%4X: ", i
);
299 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
301 fprintf(log_stream
, "%02X ", d
[j
]);
303 fputs(": ", log_stream
);
306 for (; j
< i
+ 16; j
++)
308 fputs(" ", log_stream
);
310 fputs(": ", log_stream
);
313 fputs(" ", log_stream
);
314 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
316 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
317 fputc(d
[j
], log_stream
);
319 fputc('.', log_stream
);
322 fputs(" ", log_stream
);
326 fputs("\n", log_stream
);
330 setbuf(log_stream
, NULL
);
334 // update a counter, accumulating 2^32 wraps
335 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
337 uint32_t new = *counter
+ delta
;
344 // initialise the random generator
345 static void initrandom(char *source
)
347 static char path
[sizeof(config
->random_device
)] = "*undefined*";
349 // reinitialise only if we are forced to do so or if the config has changed
350 if (source
&& !strncmp(path
, source
, sizeof(path
)))
353 // close previous source, if any
362 snprintf(path
, sizeof(path
), "%s", source
);
366 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
368 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
369 path
, strerror(errno
));
374 // fill buffer with random data
375 void random_data(uint8_t *buf
, int len
)
382 n
= read(rand_fd
, buf
, len
);
383 if (n
>= len
) return;
388 LOG(0, 0, 0, "Error reading from random source: %s\n",
391 // fall back to rand()
399 // append missing data
401 // not using the low order bits from the prng stream
402 buf
[n
++] = (rand() >> 4) & 0xff;
407 // This adds it to the routing table, advertises it
408 // via BGP if enabled, and stuffs it into the
409 // 'sessionbyip' cache.
411 // 'ip' and 'mask' must be in _host_ order.
413 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
418 if (!mask
) mask
= 0xffffffff;
420 ip
&= mask
; // Force the ip to be the first one in the route.
422 memset(&r
, 0, sizeof(r
));
423 r
.rt_dev
= config
->tundevice
;
424 r
.rt_dst
.sa_family
= AF_INET
;
425 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
426 r
.rt_gateway
.sa_family
= AF_INET
;
427 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
428 r
.rt_genmask
.sa_family
= AF_INET
;
429 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
430 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
432 r
.rt_flags
|= RTF_GATEWAY
;
433 else if (mask
== 0xffffffff)
434 r
.rt_flags
|= RTF_HOST
;
436 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
437 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
438 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
440 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
441 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
445 bgp_add_route(htonl(ip
), htonl(mask
));
447 bgp_del_route(htonl(ip
), htonl(mask
));
450 // Add/Remove the IPs to the 'sessionbyip' cache.
451 // Note that we add the zero address in the case of
452 // a network route. Roll on CIDR.
454 // Note that 's == 0' implies this is the address pool.
455 // We still cache it here, because it will pre-fill
456 // the malloc'ed tree.
460 if (!add
) // Are we deleting a route?
461 s
= 0; // Caching the session as '0' is the same as uncaching.
463 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
468 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
471 char ipv6addr
[INET6_ADDRSTRLEN
];
475 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
479 memset(&rt
, 0, sizeof(rt
));
481 memcpy(&rt
.rtmsg_dst
, &ip
, sizeof(struct in6_addr
));
482 rt
.rtmsg_dst_len
= prefixlen
;
484 rt
.rtmsg_flags
= RTF_UP
;
485 rt
.rtmsg_ifindex
= tunidx
;
487 LOG(1, 0, 0, "Route %s %s/%d\n",
489 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
492 if (ioctl(ifr6fd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &rt
) < 0)
493 LOG(0, 0, 0, "route6set() error in ioctl: %s\n",
496 // FIXME: need to add BGP routing (RFC2858)
500 if (!add
) // Are we deleting a route?
501 s
= 0; // Caching the session as '0' is the same as uncaching.
503 cache_ipv6map(ip
, prefixlen
, s
);
509 // defined in linux/ipv6.h, but tricky to include from user-space
510 // TODO: move routing to use netlink rather than ioctl
512 struct in6_addr ifr6_addr
;
513 __u32 ifr6_prefixlen
;
514 unsigned int ifr6_ifindex
;
518 // Set up TUN interface
519 static void inittun(void)
522 struct in6_ifreq ifr6
;
523 struct sockaddr_in sin
= {0};
524 memset(&ifr
, 0, sizeof(ifr
));
525 ifr
.ifr_flags
= IFF_TUN
;
527 tunfd
= open(TUNDEVICE
, O_RDWR
);
530 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
534 int flags
= fcntl(tunfd
, F_GETFL
, 0);
535 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
537 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
539 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
542 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
543 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
544 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
546 sin
.sin_family
= AF_INET
;
547 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
548 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
550 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
552 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
555 /* Bump up the qlen to deal with bursts from the network */
557 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
559 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
562 /* set MTU to modem MRU */
564 if (ioctl(ifrfd
, SIOCSIFMTU
, (void *) &ifr
) < 0)
566 LOG(0, 0, 0, "Error setting tun MTU: %s\n", strerror(errno
));
569 ifr
.ifr_flags
= IFF_UP
;
570 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
572 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
575 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
577 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno
));
580 tunidx
= ifr
.ifr_ifindex
;
582 // Only setup IPv6 on the tun device if we have a configured prefix
583 if (config
->ipv6_prefix
.s6_addr
[0]) {
584 ifr6fd
= socket(PF_INET6
, SOCK_DGRAM
, 0);
586 // Link local address is FE80::1
587 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
588 ifr6
.ifr6_addr
.s6_addr
[0] = 0xFE;
589 ifr6
.ifr6_addr
.s6_addr
[1] = 0x80;
590 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
591 ifr6
.ifr6_prefixlen
= 64;
592 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
593 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
595 LOG(0, 0, 0, "Error setting tun IPv6 link local address:"
596 " %s\n", strerror(errno
));
599 // Global address is prefix::1
600 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
601 ifr6
.ifr6_addr
= config
->ipv6_prefix
;
602 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
603 ifr6
.ifr6_prefixlen
= 64;
604 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
605 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
607 LOG(0, 0, 0, "Error setting tun IPv6 global address: %s\n",
614 static void initudp(void)
617 struct sockaddr_in addr
;
620 memset(&addr
, 0, sizeof(addr
));
621 addr
.sin_family
= AF_INET
;
622 addr
.sin_port
= htons(L2TPPORT
);
623 addr
.sin_addr
.s_addr
= config
->bind_address
;
624 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
625 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
627 int flags
= fcntl(udpfd
, F_GETFL
, 0);
628 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
630 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
632 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
637 memset(&addr
, 0, sizeof(addr
));
638 addr
.sin_family
= AF_INET
;
639 addr
.sin_port
= htons(NSCTL_PORT
);
640 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
641 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
642 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
643 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
645 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
649 // Dynamic Authorization Extensions to RADIUS
650 memset(&addr
, 0, sizeof(addr
));
651 addr
.sin_family
= AF_INET
;
652 addr
.sin_port
= htons(config
->radius_dae_port
);
653 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
654 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
655 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
656 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
658 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
663 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
667 // Find session by IP, < 1 for not found
669 // Confusingly enough, this 'ip' must be
670 // in _network_ order. This being the common
671 // case when looking it up from IP packet headers.
673 // We actually use this cache for two things.
674 // #1. For used IP addresses, this maps to the
675 // session ID that it's used by.
676 // #2. For un-used IP addresses, this maps to the
677 // index into the pool table that contains that
681 static int lookup_ipmap(in_addr_t ip
)
683 uint8_t *a
= (uint8_t *) &ip
;
684 uint8_t **d
= (uint8_t **) ip_hash
;
686 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
687 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
688 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
690 return (int) (intptr_t) d
[(size_t) *a
];
693 static int lookup_ipv6map(struct in6_addr ip
)
695 struct ipv6radix
*curnode
;
698 char ipv6addr
[INET6_ADDRSTRLEN
];
700 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
704 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
706 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
711 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
712 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
719 sessionidt
sessionbyip(in_addr_t ip
)
721 int s
= lookup_ipmap(ip
);
724 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
725 return (sessionidt
) s
;
730 sessionidt
sessionbyipv6(struct in6_addr ip
)
733 CSTAT(sessionbyipv6
);
735 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
736 (ip
.s6_addr
[0] == 0xFE &&
737 ip
.s6_addr
[1] == 0x80 &&
738 ip
.s6_addr16
[1] == 0 &&
739 ip
.s6_addr16
[2] == 0 &&
740 ip
.s6_addr16
[3] == 0)) {
741 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
743 s
= lookup_ipv6map(ip
);
746 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
753 // Take an IP address in HOST byte order and
754 // add it to the sessionid by IP cache.
756 // (It's actually cached in network order)
758 static void cache_ipmap(in_addr_t ip
, int s
)
760 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
761 uint8_t *a
= (uint8_t *) &nip
;
762 uint8_t **d
= (uint8_t **) ip_hash
;
765 for (i
= 0; i
< 3; i
++)
767 if (!d
[(size_t) a
[i
]])
769 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof(void *))))
773 d
= (uint8_t **) d
[(size_t) a
[i
]];
776 d
[(size_t) a
[3]] = (uint8_t *) (intptr_t) s
;
779 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
782 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
783 // else a map to an ip pool index.
786 static void uncache_ipmap(in_addr_t ip
)
788 cache_ipmap(ip
, 0); // Assign it to the NULL session.
791 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, int s
)
795 struct ipv6radix
*curnode
;
796 char ipv6addr
[INET6_ADDRSTRLEN
];
798 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
800 bytes
= prefixlen
>> 3;
803 if (curnode
->branch
== NULL
)
805 if (!(curnode
->branch
= calloc(256,
806 sizeof (struct ipv6radix
))))
809 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
816 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
817 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
821 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
822 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
828 // CLI list to dump current ipcache.
830 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
832 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
836 if (CLI_HELP_REQUESTED
)
837 return CLI_HELP_NO_ARGS
;
839 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
841 for (i
= 0; i
< 256; ++i
)
846 for (j
= 0; j
< 256; ++j
)
851 for (k
= 0; k
< 256; ++k
)
856 for (l
= 0; l
< 256; ++l
)
860 cli_print(cli
, "%7d %d.%d.%d.%d", (int) (intptr_t) g
[l
], i
, j
, k
, l
);
866 cli_print(cli
, "%d entries in cache", count
);
871 // Find session by username, 0 for not found
872 // walled garden users aren't authenticated, so the username is
873 // reasonably useless. Ignore them to avoid incorrect actions
875 // This is VERY inefficent. Don't call it often. :)
877 sessionidt
sessionbyuser(char *username
)
880 CSTAT(sessionbyuser
);
882 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
884 if (!session
[s
].opened
)
887 if (session
[s
].walled_garden
)
888 continue; // Skip walled garden users.
890 if (!strncmp(session
[s
].user
, username
, 128))
894 return 0; // Not found.
897 void send_garp(in_addr_t ip
)
903 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
906 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
909 memset(&ifr
, 0, sizeof(ifr
));
910 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
911 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
913 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
917 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
918 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
920 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
925 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
928 static sessiont
*sessiontbysessionidt(sessionidt s
)
930 if (!s
|| s
>= MAXSESSION
) return NULL
;
934 static sessionidt
sessionidtbysessiont(sessiont
*s
)
936 sessionidt val
= s
-session
;
937 if (s
< session
|| val
>= MAXSESSION
) return 0;
941 // actually send a control message for a specific tunnel
942 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
944 struct sockaddr_in addr
;
950 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
951 STAT(tunnel_tx_errors
);
957 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
958 STAT(tunnel_tx_errors
);
962 memset(&addr
, 0, sizeof(addr
));
963 addr
.sin_family
= AF_INET
;
964 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
965 addr
.sin_port
= htons(tunnel
[t
].port
);
967 // sequence expected, if sequence in message
968 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
970 // If this is a control message, deal with retries
973 tunnel
[t
].last
= time_now
; // control message sent
974 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
977 STAT(tunnel_retries
);
978 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
982 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
984 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
985 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
986 STAT(tunnel_tx_errors
);
990 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
991 STAT(tunnel_tx_packets
);
992 INC_STAT(tunnel_tx_bytes
, l
);
996 // Tiny helper function to write data to
999 int tun_write(uint8_t * data
, int size
)
1001 return write(tunfd
, data
, size
);
1004 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1005 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1007 int d
= (tcp
[12] >> 4) * 4;
1014 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1017 if (tcp
+ d
> buf
+ len
) // short?
1025 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1028 if (mss
+ 2 > data
) return; // short?
1032 if (*opts
== 0) return; // end of options
1033 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1036 opts
+= opts
[1]; // skip over option
1039 if (!mss
) return; // not found
1040 orig
= ntohs(*(uint16_t *) mss
);
1042 if (orig
<= MSS
) return; // mss OK
1044 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1045 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1046 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1047 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1050 *(int16_t *) mss
= htons(MSS
);
1052 // adjust checksum (see rfc1141)
1053 sum
= orig
+ (~MSS
& 0xffff);
1054 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1055 sum
= (sum
& 0xffff) + (sum
>> 16);
1056 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1059 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1063 // Skip the four extra bytes
1068 // Process this frame
1076 proto
= ntohs(*(uint16_t *) p
);
1085 LOG(4, s
, t
, "MPPP: Session %u is closing. Don't process PPP packets\n", s
);
1086 return; // closing session, PPP not processed
1089 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1090 processipin(s
, t
, p
, l
);
1092 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1096 LOG(4, s
, t
, "MPPP: Session %u is closing. Don't process PPP packets\n", s
);
1097 return; // closing session, PPP not processed
1100 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1101 processipv6in(s
, t
, p
, l
);
1105 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1109 // process outgoing (to tunnel) IP
1111 static void processipout(uint8_t *buf
, int len
)
1118 uint8_t *data
= buf
; // Keep a copy of the originals.
1121 uint8_t b1
[MAXETHER
+ 20];
1122 uint8_t b2
[MAXETHER
+ 20];
1124 CSTAT(processipout
);
1126 if (len
< MIN_IP_SIZE
)
1128 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1129 STAT(tun_rx_errors
);
1132 if (len
>= MAXETHER
)
1134 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1135 STAT(tun_rx_errors
);
1139 // Skip the tun header
1143 // Got an IP header now
1144 if (*(uint8_t *)(buf
) >> 4 != 4)
1146 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1150 ip
= *(uint32_t *)(buf
+ 16);
1151 if (!(s
= sessionbyip(ip
)))
1153 // Is this a packet for a session that doesn't exist?
1154 static int rate
= 0; // Number of ICMP packets we've sent this second.
1155 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1157 if (last
!= time_now
)
1163 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1165 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1166 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1167 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1171 t
= session
[s
].tunnel
;
1173 sp
->last_data
= time_now
;
1175 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1176 if (config
->max_packets
> 0)
1178 if (sess_local
[s
].last_packet_out
== TIME
)
1180 int max
= config
->max_packets
;
1182 // All packets for throttled sessions are handled by the
1183 // master, so further limit by using the throttle rate.
1184 // A bit of a kludge, since throttle rate is in kbps,
1185 // but should still be generous given our average DSL
1186 // packet size is 200 bytes: a limit of 28kbps equates
1187 // to around 180 packets per second.
1188 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1189 max
= sp
->throttle_out
;
1191 if (++sess_local
[s
].packets_out
> max
)
1193 sess_local
[s
].packets_dropped
++;
1199 if (sess_local
[s
].packets_dropped
)
1201 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1202 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1203 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1204 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1208 sess_local
[s
].last_packet_out
= TIME
;
1209 sess_local
[s
].packets_out
= 1;
1210 sess_local
[s
].packets_dropped
= 0;
1214 // run access-list if any
1215 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1218 // adjust MSS on SYN and SYN,ACK packets with options
1219 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1221 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1222 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1223 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1228 // Are we throttling this session?
1229 if (config
->cluster_iam_master
)
1230 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1232 master_throttle_packet(sp
->tbf_out
, data
, size
);
1236 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1238 // We are walled-gardening this
1239 master_garden_packet(s
, data
, size
);
1243 // Add on L2TP header
1246 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1248 bid
= session
[s
].bundle
;
1249 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1250 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %u\n", s
);
1253 // Partition the packet to 2 fragments
1254 uint32_t frag1len
= len
/ 2;
1255 uint32_t frag2len
= len
- frag1len
;
1256 uint8_t *p
= makeppp(b1
, sizeof(b1
), buf
, frag1len
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1260 tunnelsend(b1
, frag1len
+ (p
-b1
), t
); // send it...
1261 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1262 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %u\n", s
);
1263 q
= makeppp(b2
, sizeof(b2
), buf
+frag1len
, frag2len
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1265 tunnelsend(b2
, frag2len
+ (q
-b2
), t
); // send it...
1268 // Send it as one frame
1269 uint8_t *p
= makeppp(b1
, sizeof(b1
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1271 tunnelsend(b1
, len
+ (p
-b1
), t
); // send it...
1276 uint8_t *p
= makeppp(b1
, sizeof(b1
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1278 tunnelsend(b1
, len
+ (p
-b1
), t
); // send it...
1282 // Snooping this session, send it to intercept box
1283 if (sp
->snoop_ip
&& sp
->snoop_port
)
1284 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1286 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1287 sp
->cout_delta
+= len
;
1291 sess_local
[s
].cout
+= len
; // To send to master..
1292 sess_local
[s
].pout
++;
1295 // process outgoing (to tunnel) IPv6
1297 static void processipv6out(uint8_t * buf
, int len
)
1303 struct in6_addr ip6
;
1305 uint8_t *data
= buf
; // Keep a copy of the originals.
1308 uint8_t b
[MAXETHER
+ 20];
1310 CSTAT(processipv6out
);
1312 if (len
< MIN_IP_SIZE
)
1314 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1315 STAT(tunnel_tx_errors
);
1318 if (len
>= MAXETHER
)
1320 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1321 STAT(tunnel_tx_errors
);
1325 // Skip the tun header
1329 // Got an IP header now
1330 if (*(uint8_t *)(buf
) >> 4 != 6)
1332 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1336 ip6
= *(struct in6_addr
*)(buf
+24);
1337 s
= sessionbyipv6(ip6
);
1341 ip
= *(uint32_t *)(buf
+ 32);
1342 s
= sessionbyip(ip
);
1347 // Is this a packet for a session that doesn't exist?
1348 static int rate
= 0; // Number of ICMP packets we've sent this second.
1349 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1351 if (last
!= time_now
)
1357 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1359 // FIXME: Should send icmp6 host unreachable
1363 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1365 bundleidt bid
= session
[s
].bundle
;
1366 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1367 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1369 t
= session
[s
].tunnel
;
1371 sp
->last_data
= time_now
;
1373 // FIXME: add DoS prevention/filters?
1377 // Are we throttling this session?
1378 if (config
->cluster_iam_master
)
1379 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1381 master_throttle_packet(sp
->tbf_out
, data
, size
);
1384 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1386 // We are walled-gardening this
1387 master_garden_packet(s
, data
, size
);
1391 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1393 // Add on L2TP header
1395 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1397 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1400 // Snooping this session, send it to intercept box
1401 if (sp
->snoop_ip
&& sp
->snoop_port
)
1402 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1404 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1405 sp
->cout_delta
+= len
;
1409 sess_local
[s
].cout
+= len
; // To send to master..
1410 sess_local
[s
].pout
++;
1414 // Helper routine for the TBF filters.
1415 // Used to send queued data in to the user!
1417 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1423 uint8_t b
[MAXETHER
+ 20];
1425 if (len
< 0 || len
> MAXETHER
)
1427 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1431 // Skip the tun header
1435 ip
= *(in_addr_t
*)(buf
+ 16);
1440 t
= session
[s
].tunnel
;
1443 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1445 // Add on L2TP header
1447 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1449 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1452 // Snooping this session.
1453 if (sp
->snoop_ip
&& sp
->snoop_port
)
1454 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1456 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1457 sp
->cout_delta
+= len
;
1461 sess_local
[s
].cout
+= len
; // To send to master..
1462 sess_local
[s
].pout
++;
1465 // add an AVP (16 bit)
1466 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1468 uint16_t l
= (m
? 0x8008 : 0x0008);
1469 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1470 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1471 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1472 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1476 // add an AVP (32 bit)
1477 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1479 uint16_t l
= (m
? 0x800A : 0x000A);
1480 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1481 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1482 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1483 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1487 // add an AVP (string)
1488 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1490 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1491 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1492 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1493 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1494 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1495 c
->length
+= 6 + strlen(val
);
1499 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1501 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1502 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1503 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1504 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1505 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1506 c
->length
+= 6 + len
;
1509 // new control connection
1510 static controlt
*controlnew(uint16_t mtype
)
1514 c
= malloc(sizeof(controlt
));
1518 controlfree
= c
->next
;
1522 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1524 control16(c
, 0, mtype
, 1);
1528 // send zero block if nothing is waiting
1530 static void controlnull(tunnelidt t
)
1533 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1536 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1537 *(uint16_t *) (buf
+ 2) = htons(12); // length
1538 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1539 *(uint16_t *) (buf
+ 6) = htons(0); // session
1540 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1541 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1542 tunnelsend(buf
, 12, t
);
1545 // add a control message to a tunnel, and send if within window
1546 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1548 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1549 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1550 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1551 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1552 tunnel
[t
].ns
++; // advance sequence
1553 // link in message in to queue
1554 if (tunnel
[t
].controlc
)
1555 tunnel
[t
].controle
->next
= c
;
1557 tunnel
[t
].controls
= c
;
1559 tunnel
[t
].controle
= c
;
1560 tunnel
[t
].controlc
++;
1562 // send now if space in window
1563 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1565 tunnel
[t
].try = 0; // first send
1566 tunnelsend(c
->buf
, c
->length
, t
);
1571 // Throttle or Unthrottle a session
1573 // Throttle the data from/to through a session to no more than
1574 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1577 // If either value is -1, the current value is retained for that
1580 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1582 if (!session
[s
].opened
)
1583 return; // No-one home.
1585 if (!*session
[s
].user
)
1586 return; // User not logged in
1590 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1591 if (session
[s
].tbf_in
)
1592 free_tbf(session
[s
].tbf_in
);
1595 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1597 session
[s
].tbf_in
= 0;
1599 session
[s
].throttle_in
= rate_in
;
1604 int bytes
= rate_out
* 1024 / 8;
1605 if (session
[s
].tbf_out
)
1606 free_tbf(session
[s
].tbf_out
);
1609 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1611 session
[s
].tbf_out
= 0;
1613 session
[s
].throttle_out
= rate_out
;
1617 // add/remove filters from session (-1 = no change)
1618 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1620 if (!session
[s
].opened
)
1621 return; // No-one home.
1623 if (!*session
[s
].user
)
1624 return; // User not logged in
1627 if (filter_in
> MAXFILTER
) filter_in
= -1;
1628 if (filter_out
> MAXFILTER
) filter_out
= -1;
1629 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1630 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1634 if (session
[s
].filter_in
)
1635 ip_filters
[session
[s
].filter_in
- 1].used
--;
1638 ip_filters
[filter_in
- 1].used
++;
1640 session
[s
].filter_in
= filter_in
;
1643 if (filter_out
>= 0)
1645 if (session
[s
].filter_out
)
1646 ip_filters
[session
[s
].filter_out
- 1].used
--;
1649 ip_filters
[filter_out
- 1].used
++;
1651 session
[s
].filter_out
= filter_out
;
1655 // start tidy shutdown of session
1656 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1658 int walled_garden
= session
[s
].walled_garden
;
1661 CSTAT(sessionshutdown
);
1663 if (!session
[s
].opened
)
1665 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1666 return; // not a live session
1669 if (!session
[s
].die
)
1671 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1672 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1673 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1676 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1678 // RADIUS Stop message
1679 uint16_t r
= radiusnew(s
);
1682 // stop, if not already trying
1683 if (radius
[r
].state
!= RADIUSSTOP
)
1685 radius
[r
].term_cause
= term_cause
;
1686 radius
[r
].term_msg
= reason
;
1687 radiussend(r
, RADIUSSTOP
);
1691 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1693 // Save counters to dump to accounting file
1694 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1695 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1699 { // IP allocated, clear and unroute
1702 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1704 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1705 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1708 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1709 session
[s
].route
[r
].ip
= 0;
1712 if (session
[s
].ip_pool_index
== -1) // static ip
1714 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1720 // unroute IPv6, if setup
1721 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
)
1722 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1725 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1726 throttle_session(s
, 0, 0);
1730 controlt
*c
= controlnew(14); // sending CDN
1734 *(uint16_t *) buf
= htons(cdn_result
);
1735 *(uint16_t *) (buf
+2) = htons(cdn_error
);
1736 controlb(c
, 1, buf
, 4, 1);
1739 control16(c
, 1, cdn_result
, 1);
1741 control16(c
, 14, s
, 1); // assigned session (our end)
1742 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
1745 if (!session
[s
].die
)
1746 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1748 // update filter refcounts
1749 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1750 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1753 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
1754 sess_local
[s
].lcp
.restart
= 0;
1755 sess_local
[s
].ipcp
.restart
= 0;
1756 sess_local
[s
].ipv6cp
.restart
= 0;
1757 sess_local
[s
].ccp
.restart
= 0;
1759 cluster_send_session(s
);
1762 void sendipcp(sessionidt s
, tunnelidt t
)
1764 uint8_t buf
[MAXETHER
];
1768 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
1770 if (!session
[s
].unique_id
)
1772 if (!++last_id
) ++last_id
; // skip zero
1773 session
[s
].unique_id
= last_id
;
1776 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
1780 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
1781 *(uint16_t *) (q
+ 2) = htons(10); // packet length
1782 q
[4] = 3; // ip address option
1783 q
[5] = 6; // option length
1784 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1785 config
->bind_address
? config
->bind_address
:
1786 my_address
; // send my IP
1788 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1789 restart_timer(s
, ipcp
);
1792 void sendipv6cp(sessionidt s
, tunnelidt t
)
1794 uint8_t buf
[MAXETHER
];
1798 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
1800 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
1804 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
1805 // only send one type
1807 *(uint16_t *) (q
+ 2) = htons(14);
1808 q
[4] = 1; // interface identifier option
1809 q
[5] = 10; // option length
1810 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
1811 *(uint32_t *) (q
+ 10) = 0;
1814 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
1815 restart_timer(s
, ipv6cp
);
1818 static void sessionclear(sessionidt s
)
1820 memset(&session
[s
], 0, sizeof(session
[s
]));
1821 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
1822 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
1824 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1825 session
[s
].next
= sessionfree
;
1829 // kill a session now
1830 void sessionkill(sessionidt s
, char *reason
)
1836 if (!session
[s
].opened
) // not alive
1839 if (session
[s
].next
)
1841 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
1845 session
[s
].die
= TIME
;
1846 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
1847 if (sess_local
[s
].radius
)
1848 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
1850 LOG(2, s
, session
[s
].tunnel
, "Kill session %u (%s): %s\n", s
, session
[s
].user
, reason
);
1851 if ((b
= session
[s
].bundle
))
1853 // This session was part of a bundle
1854 bundle
[b
].num_of_links
--;
1855 LOG(3, s
, 0, "MPPP: Dropping member link: %u from bundle %u\n", s
, b
);
1856 if (bundle
[b
].num_of_links
== 0)
1859 LOG(3, s
, 0, "MPPP: Kill bundle: %u (No remaing member links)\n", b
);
1863 // Adjust the members array to accomodate the new change
1864 uint8_t mem_num
= 0;
1865 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
1866 if (bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
1869 for (ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
1871 if (bundle
[b
].members
[ml
] == s
)
1877 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
1878 LOG(3, s
, 0, "MPPP: Adjusted member links array\n");
1881 cluster_send_bundle(b
);
1884 cluster_send_session(s
);
1887 static void tunnelclear(tunnelidt t
)
1890 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1891 tunnel
[t
].state
= TUNNELFREE
;
1894 static void bundleclear(bundleidt b
)
1897 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
1898 bundle
[b
].state
= BUNDLEFREE
;
1901 // kill a tunnel now
1902 static void tunnelkill(tunnelidt t
, char *reason
)
1909 tunnel
[t
].state
= TUNNELDIE
;
1911 // free control messages
1912 while ((c
= tunnel
[t
].controls
))
1914 controlt
* n
= c
->next
;
1915 tunnel
[t
].controls
= n
;
1916 tunnel
[t
].controlc
--;
1917 c
->next
= controlfree
;
1921 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1922 if (session
[s
].tunnel
== t
)
1923 sessionkill(s
, reason
);
1927 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
1928 cli_tunnel_actions
[t
].action
= 0;
1929 cluster_send_tunnel(t
);
1932 // shut down a tunnel cleanly
1933 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
1937 CSTAT(tunnelshutdown
);
1939 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1941 // never set up, can immediately kill
1942 tunnelkill(t
, reason
);
1945 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
1948 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1949 if (session
[s
].tunnel
== t
)
1950 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
1952 tunnel
[t
].state
= TUNNELDIE
;
1953 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
1954 cluster_send_tunnel(t
);
1955 // TBA - should we wait for sessions to stop?
1958 controlt
*c
= controlnew(4); // sending StopCCN
1963 *(uint16_t *) buf
= htons(result
);
1964 *(uint16_t *) (buf
+2) = htons(error
);
1967 int m
= strlen(msg
);
1968 if (m
+ 4 > sizeof(buf
))
1969 m
= sizeof(buf
) - 4;
1971 memcpy(buf
+4, msg
, m
);
1975 controlb(c
, 1, buf
, l
, 1);
1978 control16(c
, 1, result
, 1);
1980 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1981 controladd(c
, 0, t
); // send the message
1985 // read and process packet on tunnel (UDP)
1986 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
1988 uint8_t *chapresponse
= NULL
;
1989 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1990 uint8_t *p
= buf
+ 2;
1997 LOG_HEX(5, "UDP Data", buf
, len
);
1998 STAT(tunnel_rx_packets
);
1999 INC_STAT(tunnel_rx_bytes
, len
);
2002 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2003 STAT(tunnel_rx_errors
);
2006 if ((buf
[1] & 0x0F) != 2)
2008 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2009 STAT(tunnel_rx_errors
);
2014 l
= ntohs(*(uint16_t *) p
);
2017 t
= ntohs(*(uint16_t *) p
);
2019 s
= ntohs(*(uint16_t *) p
);
2021 if (s
>= MAXSESSION
)
2023 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2024 STAT(tunnel_rx_errors
);
2029 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2030 STAT(tunnel_rx_errors
);
2035 ns
= ntohs(*(uint16_t *) p
);
2037 nr
= ntohs(*(uint16_t *) p
);
2042 uint16_t o
= ntohs(*(uint16_t *) p
);
2047 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2048 STAT(tunnel_rx_errors
);
2053 // used to time out old tunnels
2054 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2055 tunnel
[t
].lastrec
= time_now
;
2059 uint16_t message
= 0xFFFF; // message type
2061 uint8_t mandatory
= 0;
2062 uint16_t asession
= 0; // assigned session
2063 uint32_t amagic
= 0; // magic number
2064 uint8_t aflags
= 0; // flags from last LCF
2065 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2066 char called
[MAXTEL
] = ""; // called number
2067 char calling
[MAXTEL
] = ""; // calling number
2069 if (!config
->cluster_iam_master
)
2071 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2075 // control messages must have bits 0x80|0x40|0x08
2076 // (type, length and sequence) set, and bits 0x02|0x01
2077 // (offset and priority) clear
2078 if ((*buf
& 0xCB) != 0xC8)
2080 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2081 STAT(tunnel_rx_errors
);
2085 // check for duplicate tunnel open message
2091 // Is this a duplicate of the first packet? (SCCRQ)
2093 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2095 if (tunnel
[i
].state
!= TUNNELOPENING
||
2096 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2097 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2100 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2105 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2106 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2108 // if no tunnel specified, assign one
2111 if (!(t
= new_tunnel()))
2113 LOG(1, 0, 0, "No more tunnels\n");
2114 STAT(tunnel_overflow
);
2118 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2119 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2120 tunnel
[t
].window
= 4; // default window
2121 STAT(tunnel_created
);
2122 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2123 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2126 // If the 'ns' just received is not the 'nr' we're
2127 // expecting, just send an ack and drop it.
2129 // if 'ns' is less, then we got a retransmitted packet.
2130 // if 'ns' is greater than missed a packet. Either way
2131 // we should ignore it.
2132 if (ns
!= tunnel
[t
].nr
)
2134 // is this the sequence we were expecting?
2135 STAT(tunnel_rx_errors
);
2136 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2137 t
, ns
, tunnel
[t
].nr
);
2139 if (l
) // Is this not a ZLB?
2144 // check sequence of this message
2146 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2147 // some to clear maybe?
2148 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2150 controlt
*c
= tunnel
[t
].controls
;
2151 tunnel
[t
].controls
= c
->next
;
2152 tunnel
[t
].controlc
--;
2153 c
->next
= controlfree
;
2156 tunnel
[t
].try = 0; // we have progress
2159 // receiver advance (do here so quoted correctly in any sends below)
2160 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2161 if (skip
< 0) skip
= 0;
2162 if (skip
< tunnel
[t
].controlc
)
2164 // some control packets can now be sent that were previous stuck out of window
2165 int tosend
= tunnel
[t
].window
- skip
;
2166 controlt
*c
= tunnel
[t
].controls
;
2174 tunnel
[t
].try = 0; // first send
2175 tunnelsend(c
->buf
, c
->length
, t
);
2180 if (!tunnel
[t
].controlc
)
2181 tunnel
[t
].retry
= 0; // caught up
2184 { // if not a null message
2189 // Default disconnect cause/message on receipt of CDN. Set to
2190 // more specific value from attribute 1 (result code) or 46
2191 // (disconnect cause) if present below.
2192 int disc_cause_set
= 0;
2193 int disc_cause
= TERM_NAS_REQUEST
;
2194 char const *disc_reason
= "Closed (Received CDN).";
2197 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2199 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2206 LOG(1, s
, t
, "Invalid length in AVP\n");
2207 STAT(tunnel_rx_errors
);
2212 if (flags
& 0x3C) // reserved bits, should be clear
2214 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2216 result
= 2; // general error
2217 error
= 3; // reserved field non-zero
2222 if (*(uint16_t *) (b
))
2224 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2226 result
= 2; // general error
2227 error
= 6; // generic vendor-specific error
2228 msg
= "unsupported vendor-specific";
2232 mtype
= ntohs(*(uint16_t *) (b
));
2240 // handle hidden AVPs
2241 if (!*config
->l2tp_secret
)
2243 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2245 result
= 2; // general error
2246 error
= 6; // generic vendor-specific error
2247 msg
= "secret not specified";
2250 if (!session
[s
].random_vector_length
)
2252 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2254 result
= 2; // general error
2255 error
= 6; // generic
2256 msg
= "no random vector";
2261 LOG(2, s
, t
, "Short hidden AVP.\n");
2263 result
= 2; // general error
2264 error
= 2; // length is wrong
2270 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2272 orig_len
= ntohs(*(uint16_t *) b
);
2273 if (orig_len
> n
+ 2)
2275 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2279 result
= 2; // general error
2280 error
= 2; // length is wrong
2289 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2290 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2294 case 0: // message type
2295 message
= ntohs(*(uint16_t *) b
);
2296 mandatory
= flags
& 0x80;
2297 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2299 case 1: // result code
2301 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2302 char const *resdesc
= "(unknown)";
2303 char const *errdesc
= NULL
;
2308 resdesc
= l2tp_stopccn_result_code(rescode
);
2309 cause
= TERM_LOST_SERVICE
;
2311 else if (message
== 14)
2313 resdesc
= l2tp_cdn_result_code(rescode
);
2315 cause
= TERM_LOST_CARRIER
;
2317 cause
= TERM_ADMIN_RESET
;
2320 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2323 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2324 errdesc
= l2tp_error_code(errcode
);
2325 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2328 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2330 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2332 disc_cause_set
= mtype
;
2333 disc_reason
= errdesc
? errdesc
: resdesc
;
2340 case 2: // protocol version
2342 version
= ntohs(*(uint16_t *) (b
));
2343 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2344 if (version
&& version
!= 0x0100)
2345 { // allow 0.0 and 1.0
2346 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2348 result
= 5; // unspported protocol version
2349 error
= 0x0100; // supported version
2355 case 3: // framing capabilities
2357 case 4: // bearer capabilities
2359 case 5: // tie breaker
2360 // We never open tunnels, so we don't care about tie breakers
2362 case 6: // firmware revision
2364 case 7: // host name
2365 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2366 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2367 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2368 // TBA - to send to RADIUS
2370 case 8: // vendor name
2371 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2372 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2373 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2375 case 9: // assigned tunnel
2376 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2377 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2379 case 10: // rx window
2380 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2381 if (!tunnel
[t
].window
)
2382 tunnel
[t
].window
= 1; // window of 0 is silly
2383 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2385 case 11: // Challenge
2387 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2388 build_chap_response(b
, 2, n
, &chapresponse
);
2391 case 13: // Response
2392 // Why did they send a response? We never challenge.
2393 LOG(2, s
, t
, " received unexpected challenge response\n");
2396 case 14: // assigned session
2397 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2398 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2400 case 15: // call serial number
2401 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2403 case 18: // bearer type
2404 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2407 case 19: // framing type
2408 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2411 case 21: // called number
2412 memset(called
, 0, sizeof(called
));
2413 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2414 LOG(4, s
, t
, " Called <%s>\n", called
);
2416 case 22: // calling number
2417 memset(calling
, 0, sizeof(calling
));
2418 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2419 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2423 case 24: // tx connect speed
2426 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2430 // AS5300s send connect speed as a string
2432 memset(tmp
, 0, sizeof(tmp
));
2433 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2434 session
[s
].tx_connect_speed
= atol(tmp
);
2436 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2438 case 38: // rx connect speed
2441 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2445 // AS5300s send connect speed as a string
2447 memset(tmp
, 0, sizeof(tmp
));
2448 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2449 session
[s
].rx_connect_speed
= atol(tmp
);
2451 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2453 case 25: // Physical Channel ID
2455 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2456 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2459 case 29: // Proxy Authentication Type
2461 uint16_t atype
= ntohs(*(uint16_t *)b
);
2462 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2465 case 30: // Proxy Authentication Name
2468 memset(authname
, 0, sizeof(authname
));
2469 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2470 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2474 case 31: // Proxy Authentication Challenge
2476 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2479 case 32: // Proxy Authentication ID
2481 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2482 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2485 case 33: // Proxy Authentication Response
2486 LOG(4, s
, t
, " Proxy Auth Response\n");
2488 case 27: // last sent lcp
2489 { // find magic number
2490 uint8_t *p
= b
, *e
= p
+ n
;
2491 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2493 if (*p
== 5 && p
[1] == 6) // Magic-Number
2494 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2495 else if (*p
== 7) // Protocol-Field-Compression
2496 aflags
|= SESSION_PFC
;
2497 else if (*p
== 8) // Address-and-Control-Field-Compression
2498 aflags
|= SESSION_ACFC
;
2503 case 28: // last recv lcp confreq
2505 case 26: // Initial Received LCP CONFREQ
2507 case 39: // seq required - we control it as an LNS anyway...
2509 case 36: // Random Vector
2510 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2511 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2512 if (n
> sizeof(session
[s
].random_vector
))
2513 n
= sizeof(session
[s
].random_vector
);
2514 memcpy(session
[s
].random_vector
, b
, n
);
2515 session
[s
].random_vector_length
= n
;
2517 case 46: // ppp disconnect cause
2520 uint16_t code
= ntohs(*(uint16_t *) b
);
2521 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2522 uint8_t dir
= *(b
+ 4);
2524 LOG(4, s
, t
, " PPP disconnect cause "
2525 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2526 code
, proto
, dir
, n
- 5, b
+ 5);
2528 disc_cause_set
= mtype
;
2532 case 1: // admin disconnect
2533 disc_cause
= TERM_ADMIN_RESET
;
2534 disc_reason
= "Administrative disconnect";
2536 case 3: // lcp terminate
2537 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2538 disc_cause
= TERM_USER_REQUEST
;
2539 disc_reason
= "Normal disconnection";
2541 case 4: // compulsory encryption unavailable
2542 if (dir
!= 1) break; // 1=refused by peer, 2=local
2543 disc_cause
= TERM_USER_ERROR
;
2544 disc_reason
= "Compulsory encryption refused";
2546 case 5: // lcp: fsm timeout
2547 disc_cause
= TERM_PORT_ERROR
;
2548 disc_reason
= "LCP: FSM timeout";
2550 case 6: // lcp: no recognisable lcp packets received
2551 disc_cause
= TERM_PORT_ERROR
;
2552 disc_reason
= "LCP: no recognisable LCP packets";
2554 case 7: // lcp: magic-no error (possibly looped back)
2555 disc_cause
= TERM_PORT_ERROR
;
2556 disc_reason
= "LCP: magic-no error (possible loop)";
2558 case 8: // lcp: echo request timeout
2559 disc_cause
= TERM_PORT_ERROR
;
2560 disc_reason
= "LCP: echo request timeout";
2562 case 13: // auth: fsm timeout
2563 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2564 disc_reason
= "Authentication: FSM timeout";
2566 case 15: // auth: unacceptable auth protocol
2567 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2568 disc_reason
= "Unacceptable authentication protocol";
2570 case 16: // auth: authentication failed
2571 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2572 disc_reason
= "Authentication failed";
2574 case 17: // ncp: fsm timeout
2575 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2576 disc_reason
= "NCP: FSM timeout";
2578 case 18: // ncp: no ncps available
2579 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2580 disc_reason
= "NCP: no NCPs available";
2582 case 19: // ncp: failure to converge on acceptable address
2583 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2584 disc_reason
= (dir
== 1)
2585 ? "NCP: too many Configure-Naks received from peer"
2586 : "NCP: too many Configure-Naks sent to peer";
2588 case 20: // ncp: user not permitted to use any address
2589 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2590 disc_reason
= (dir
== 1)
2591 ? "NCP: local link address not acceptable to peer"
2592 : "NCP: remote link address not acceptable";
2599 static char e
[] = "unknown AVP 0xXXXX";
2600 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2602 result
= 2; // general error
2603 error
= 8; // unknown mandatory AVP
2604 sprintf((msg
= e
) + 14, "%04x", mtype
);
2611 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2615 case 1: // SCCRQ - Start Control Connection Request
2616 tunnel
[t
].state
= TUNNELOPENING
;
2617 if (main_quit
!= QUIT_SHUTDOWN
)
2619 controlt
*c
= controlnew(2); // sending SCCRP
2620 control16(c
, 2, version
, 1); // protocol version
2621 control32(c
, 3, 3, 1); // framing
2622 controls(c
, 7, hostname
, 1); // host name
2623 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2624 control16(c
, 9, t
, 1); // assigned tunnel
2625 controladd(c
, 0, t
); // send the resply
2629 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2633 tunnel
[t
].state
= TUNNELOPEN
;
2636 tunnel
[t
].state
= TUNNELOPEN
;
2637 controlnull(t
); // ack
2640 controlnull(t
); // ack
2641 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2644 controlnull(t
); // simply ACK
2656 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2658 controlt
*c
= controlnew(11); // ICRP
2661 sessionfree
= session
[s
].next
;
2662 memset(&session
[s
], 0, sizeof(session
[s
]));
2664 if (s
> config
->cluster_highest_sessionid
)
2665 config
->cluster_highest_sessionid
= s
;
2667 session
[s
].opened
= time_now
;
2668 session
[s
].tunnel
= t
;
2669 session
[s
].far
= asession
;
2670 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2671 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2672 control16(c
, 14, s
, 1); // assigned session
2673 controladd(c
, asession
, t
); // send the reply
2675 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2676 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2678 session
[s
].ppp
.phase
= Establish
;
2679 session
[s
].ppp
.lcp
= Starting
;
2681 STAT(session_created
);
2686 controlt
*c
= controlnew(14); // CDN
2689 STAT(session_overflow
);
2690 LOG(1, 0, t
, "No free sessions\n");
2691 control16(c
, 1, 4, 0); // temporary lack of resources
2694 control16(c
, 1, 2, 7); // shutting down, try another
2696 controladd(c
, asession
, t
); // send the message
2703 if (amagic
== 0) amagic
= time_now
;
2704 session
[s
].magic
= amagic
; // set magic number
2705 session
[s
].flags
= aflags
; // set flags received
2706 session
[s
].mru
= PPPoE_MRU
; // default
2707 controlnull(t
); // ack
2710 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
2711 sess_local
[s
].ppp_mru
= MRU
;
2713 // Set multilink options before sending initial LCP packet
2714 sess_local
[s
].mp_mrru
= 1614;
2715 sess_local
[s
].mp_epdis
= config
->bind_address
? config
->bind_address
: my_address
;
2718 change_state(s
, lcp
, RequestSent
);
2722 controlnull(t
); // ack
2723 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
2726 LOG(1, s
, t
, "Missing message type\n");
2729 STAT(tunnel_rx_errors
);
2731 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2733 LOG(1, s
, t
, "Unknown message type %u\n", message
);
2736 if (chapresponse
) free(chapresponse
);
2737 cluster_send_tunnel(t
);
2741 LOG(4, s
, t
, " Got a ZLB ack\n");
2748 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
2749 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
2750 { // HDLC address header, discard
2756 LOG(1, s
, t
, "Short ppp length %d\n", l
);
2757 STAT(tunnel_rx_errors
);
2767 proto
= ntohs(*(uint16_t *) p
);
2772 if (s
&& !session
[s
].opened
) // Is something wrong??
2774 if (!config
->cluster_iam_master
)
2776 // Pass it off to the master to deal with..
2777 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2782 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
2783 STAT(tunnel_rx_errors
);
2787 if (proto
== PPPPAP
)
2789 session
[s
].last_packet
= time_now
;
2790 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2791 processpap(s
, t
, p
, l
);
2793 else if (proto
== PPPCHAP
)
2795 session
[s
].last_packet
= time_now
;
2796 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2797 processchap(s
, t
, p
, l
);
2799 else if (proto
== PPPLCP
)
2801 session
[s
].last_packet
= time_now
;
2802 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2803 processlcp(s
, t
, p
, l
);
2805 else if (proto
== PPPIPCP
)
2807 session
[s
].last_packet
= time_now
;
2808 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2809 processipcp(s
, t
, p
, l
);
2811 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
2813 session
[s
].last_packet
= time_now
;
2814 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2815 processipv6cp(s
, t
, p
, l
);
2817 else if (proto
== PPPCCP
)
2819 session
[s
].last_packet
= time_now
;
2820 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2821 processccp(s
, t
, p
, l
);
2823 else if (proto
== PPPIP
)
2827 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2828 return; // closing session, PPP not processed
2831 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2832 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2834 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2838 processipin(s
, t
, p
, l
);
2840 else if (proto
== PPPMP
)
2844 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2845 return; // closing session, PPP not processed
2848 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2849 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2851 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2855 processmpin(s
, t
, p
, l
);
2857 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
2861 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2862 return; // closing session, PPP not processed
2865 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2866 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2868 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2872 processipv6in(s
, t
, p
, l
);
2874 else if (session
[s
].ppp
.lcp
== Opened
)
2876 session
[s
].last_packet
= time_now
;
2877 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2878 protoreject(s
, t
, p
, l
, proto
);
2882 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
2883 proto
, ppp_state(session
[s
].ppp
.lcp
));
2888 // read and process packet on tun
2889 static void processtun(uint8_t * buf
, int len
)
2891 LOG_HEX(5, "Receive TUN Data", buf
, len
);
2892 STAT(tun_rx_packets
);
2893 INC_STAT(tun_rx_bytes
, len
);
2901 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
2902 STAT(tun_rx_errors
);
2906 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
2907 processipout(buf
, len
);
2908 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
2909 && config
->ipv6_prefix
.s6_addr
[0])
2910 processipv6out(buf
, len
);
2915 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
2916 // that we look at the whole of the tunnel, radius and session tables
2918 static void regular_cleanups(double period
)
2920 // Next tunnel, radius and session to check for actions on.
2921 static tunnelidt t
= 0;
2923 static sessionidt s
= 0;
2936 // divide up tables into slices based on the last run
2937 t_slice
= config
->cluster_highest_tunnelid
* period
;
2938 r_slice
= (MAXRADIUS
- 1) * period
;
2939 s_slice
= config
->cluster_highest_sessionid
* period
;
2943 else if (t_slice
> config
->cluster_highest_tunnelid
)
2944 t_slice
= config
->cluster_highest_tunnelid
;
2948 else if (r_slice
> (MAXRADIUS
- 1))
2949 r_slice
= MAXRADIUS
- 1;
2953 else if (s_slice
> config
->cluster_highest_sessionid
)
2954 s_slice
= config
->cluster_highest_sessionid
;
2956 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
2958 for (i
= 0; i
< t_slice
; i
++)
2961 if (t
> config
->cluster_highest_tunnelid
)
2964 // check for expired tunnels
2965 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2967 STAT(tunnel_timeout
);
2968 tunnelkill(t
, "Expired");
2972 // check for message resend
2973 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2975 // resend pending messages as timeout on reply
2976 if (tunnel
[t
].retry
<= TIME
)
2978 controlt
*c
= tunnel
[t
].controls
;
2979 uint8_t w
= tunnel
[t
].window
;
2980 tunnel
[t
].try++; // another try
2981 if (tunnel
[t
].try > 5)
2982 tunnelkill(t
, "Timeout on control message"); // game over
2986 tunnelsend(c
->buf
, c
->length
, t
);
2994 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
2996 controlt
*c
= controlnew(6); // sending HELLO
2997 controladd(c
, 0, t
); // send the message
2998 LOG(3, 0, t
, "Sending HELLO message\n");
3002 // Check for tunnel changes requested from the CLI
3003 if ((a
= cli_tunnel_actions
[t
].action
))
3005 cli_tunnel_actions
[t
].action
= 0;
3006 if (a
& CLI_TUN_KILL
)
3008 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3009 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3015 for (i
= 0; i
< r_slice
; i
++)
3021 if (!radius
[r
].state
)
3024 if (radius
[r
].retry
<= TIME
)
3031 for (i
= 0; i
< s_slice
; i
++)
3034 if (s
> config
->cluster_highest_sessionid
)
3037 if (!session
[s
].opened
) // Session isn't in use
3040 // check for expired sessions
3043 if (session
[s
].die
<= TIME
)
3045 sessionkill(s
, "Expired");
3051 // check for timed out sessions
3052 if (session
[s
].timeout
)
3054 bundleidt bid
= session
[s
].bundle
;
3057 clockt curr_time
= time_now
;
3058 if (curr_time
- bundle
[bid
].last_check
>= 1)
3060 bundle
[bid
].online_time
+= (curr_time
-bundle
[bid
].last_check
)*bundle
[bid
].num_of_links
;
3061 bundle
[bid
].last_check
= curr_time
;
3062 if (bundle
[bid
].online_time
>= session
[s
].timeout
)
3065 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3067 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3074 else if (session
[s
].timeout
<= time_now
- session
[s
].opened
)
3076 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3083 if (sess_local
[s
].lcp
.restart
<= time_now
)
3085 int next_state
= session
[s
].ppp
.lcp
;
3086 switch (session
[s
].ppp
.lcp
)
3090 next_state
= RequestSent
;
3093 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3095 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3096 sendlcp(s
, session
[s
].tunnel
);
3097 change_state(s
, lcp
, next_state
);
3101 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3102 STAT(session_timeout
);
3112 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3114 int next_state
= session
[s
].ppp
.ipcp
;
3115 switch (session
[s
].ppp
.ipcp
)
3119 next_state
= RequestSent
;
3122 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3124 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3125 sendipcp(s
, session
[s
].tunnel
);
3126 change_state(s
, ipcp
, next_state
);
3130 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3131 STAT(session_timeout
);
3141 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3143 int next_state
= session
[s
].ppp
.ipv6cp
;
3144 switch (session
[s
].ppp
.ipv6cp
)
3148 next_state
= RequestSent
;
3151 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3153 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3154 sendipv6cp(s
, session
[s
].tunnel
);
3155 change_state(s
, ipv6cp
, next_state
);
3159 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3160 change_state(s
, ipv6cp
, Stopped
);
3167 if (sess_local
[s
].ccp
.restart
<= time_now
)
3169 int next_state
= session
[s
].ppp
.ccp
;
3170 switch (session
[s
].ppp
.ccp
)
3174 next_state
= RequestSent
;
3177 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3179 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3180 sendccp(s
, session
[s
].tunnel
);
3181 change_state(s
, ccp
, next_state
);
3185 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3186 change_state(s
, ccp
, Stopped
);
3193 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3194 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3196 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3197 STAT(session_timeout
);
3202 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3203 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3204 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3206 uint8_t b
[MAXETHER
];
3208 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3212 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3213 *(uint16_t *)(q
+ 2) = htons(8); // Length
3214 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3216 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3217 (int)(time_now
- session
[s
].last_packet
));
3218 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3219 sess_local
[s
].last_echo
= time_now
;
3223 // Drop sessions who have reached session_timeout seconds
3224 if (session
[s
].session_timeout
&& (time_now
- session
[s
].opened
>= session
[s
].session_timeout
))
3226 sessionshutdown(s
, "Session Timeout Reached", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3227 STAT(session_timeout
);
3232 // Drop sessions who have reached idle_timeout seconds
3233 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3235 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3236 STAT(session_timeout
);
3241 // Check for actions requested from the CLI
3242 if ((a
= cli_session_actions
[s
].action
))
3246 cli_session_actions
[s
].action
= 0;
3247 if (a
& CLI_SESS_KILL
)
3249 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3250 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3251 a
= 0; // dead, no need to check for other actions
3255 if (a
& CLI_SESS_NOSNOOP
)
3257 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3258 session
[s
].snoop_ip
= 0;
3259 session
[s
].snoop_port
= 0;
3263 else if (a
& CLI_SESS_SNOOP
)
3265 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3266 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3267 cli_session_actions
[s
].snoop_port
);
3269 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3270 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3275 if (a
& CLI_SESS_NOTHROTTLE
)
3277 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3278 throttle_session(s
, 0, 0);
3282 else if (a
& CLI_SESS_THROTTLE
)
3284 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3285 cli_session_actions
[s
].throttle_in
,
3286 cli_session_actions
[s
].throttle_out
);
3288 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3293 if (a
& CLI_SESS_NOFILTER
)
3295 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3296 filter_session(s
, 0, 0);
3300 else if (a
& CLI_SESS_FILTER
)
3302 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3303 cli_session_actions
[s
].filter_in
,
3304 cli_session_actions
[s
].filter_out
);
3306 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3312 cluster_send_session(s
);
3315 // RADIUS interim accounting
3316 if (config
->radius_accounting
&& config
->radius_interim
> 0
3317 && session
[s
].ip
&& !session
[s
].walled_garden
3318 && !sess_local
[s
].radius
// RADIUS already in progress
3319 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
)
3321 int rad
= radiusnew(s
);
3324 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3325 STAT(radius_overflow
);
3329 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3330 session
[s
].user
, session
[s
].unique_id
);
3332 radiussend(rad
, RADIUSINTERIM
);
3333 sess_local
[s
].last_interim
= time_now
;
3338 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3339 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3343 // Are we in the middle of a tunnel update, or radius
3346 static int still_busy(void)
3349 static clockt last_talked
= 0;
3350 static clockt start_busy_wait
= 0;
3352 if (!config
->cluster_iam_master
)
3355 static time_t stopped_bgp
= 0;
3360 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3362 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3363 if (bgp_peers
[i
].state
== Established
)
3364 bgp_stop(&bgp_peers
[i
]);
3366 stopped_bgp
= time_now
;
3368 // we don't want to become master
3369 cluster_send_ping(0);
3374 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
3382 if (main_quit
== QUIT_SHUTDOWN
)
3384 static int dropped
= 0;
3389 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3390 for (i
= 1; i
< MAXTUNNEL
; i
++)
3391 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3392 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3398 if (start_busy_wait
== 0)
3399 start_busy_wait
= TIME
;
3401 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3403 if (!tunnel
[i
].controlc
)
3406 if (last_talked
!= TIME
)
3408 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3414 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3415 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3417 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3421 for (i
= 1; i
< MAXRADIUS
; i
++)
3423 if (radius
[i
].state
== RADIUSNULL
)
3425 if (radius
[i
].state
== RADIUSWAIT
)
3428 if (last_talked
!= TIME
)
3430 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3440 # include <sys/epoll.h>
3442 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3443 # include "fake_epoll.h"
3446 // the base set of fds polled: cli, cluster, tun, udp, control, dae
3449 // additional polled fds
3451 # define EXTRA_FDS BGP_NUM_PEERS
3453 # define EXTRA_FDS 0
3456 // main loop - gets packets on tun or udp and processes them
3457 static void mainloop(void)
3461 clockt next_cluster_ping
= 0; // send initial ping immediately
3462 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3463 int maxevent
= sizeof(events
)/sizeof(*events
);
3465 if ((epollfd
= epoll_create(maxevent
)) < 0)
3467 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3471 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d\n",
3472 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
);
3474 /* setup our fds to poll for input */
3476 static struct event_data d
[BASE_FDS
];
3477 struct epoll_event e
;
3484 d
[i
].type
= FD_TYPE_CLI
;
3485 e
.data
.ptr
= &d
[i
++];
3486 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3489 d
[i
].type
= FD_TYPE_CLUSTER
;
3490 e
.data
.ptr
= &d
[i
++];
3491 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3493 d
[i
].type
= FD_TYPE_TUN
;
3494 e
.data
.ptr
= &d
[i
++];
3495 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3497 d
[i
].type
= FD_TYPE_UDP
;
3498 e
.data
.ptr
= &d
[i
++];
3499 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3501 d
[i
].type
= FD_TYPE_CONTROL
;
3502 e
.data
.ptr
= &d
[i
++];
3503 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3505 d
[i
].type
= FD_TYPE_DAE
;
3506 e
.data
.ptr
= &d
[i
++];
3507 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3511 signal(SIGPIPE
, SIG_IGN
);
3512 bgp_setup(config
->as_number
);
3513 if (config
->bind_address
)
3514 bgp_add_route(config
->bind_address
, 0xffffffff);
3516 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3518 if (config
->neighbour
[i
].name
[0])
3519 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3520 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3521 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3525 while (!main_quit
|| still_busy())
3535 config
->reload_config
++;
3538 if (config
->reload_config
)
3540 config
->reload_config
= 0;
3548 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3549 STAT(select_called
);
3554 if (errno
== EINTR
||
3555 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3558 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3564 struct sockaddr_in addr
;
3565 struct in_addr local
;
3570 int cluster_ready
= 0;
3573 int cluster_pkts
= 0;
3575 uint32_t bgp_events
[BGP_NUM_PEERS
];
3576 memset(bgp_events
, 0, sizeof(bgp_events
));
3579 for (c
= n
, i
= 0; i
< c
; i
++)
3581 struct event_data
*d
= events
[i
].data
.ptr
;
3585 case FD_TYPE_CLI
: // CLI connections
3589 alen
= sizeof(addr
);
3590 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3596 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3602 // these are handled below, with multiple interleaved reads
3603 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3604 case FD_TYPE_TUN
: tun_ready
++; break;
3605 case FD_TYPE_UDP
: udp_ready
++; break;
3607 case FD_TYPE_CONTROL
: // nsctl commands
3608 alen
= sizeof(addr
);
3609 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3610 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3614 case FD_TYPE_DAE
: // DAE requests
3615 alen
= sizeof(addr
);
3616 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3617 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3621 case FD_TYPE_RADIUS
: // RADIUS response
3622 alen
= sizeof(addr
);
3623 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3624 if (s
>= 0 && config
->cluster_iam_master
)
3626 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3627 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3628 processrad(buf
, s
, d
->index
);
3630 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3631 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3639 bgp_events
[d
->index
] = events
[i
].events
;
3645 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3650 bgp_process(bgp_events
);
3653 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3658 alen
= sizeof(addr
);
3659 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3661 processudp(buf
, s
, &addr
);
3674 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3689 alen
= sizeof(addr
);
3690 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3692 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3703 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3704 STAT(multi_read_used
);
3706 if (c
>= config
->multi_read_count
)
3708 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3709 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3711 STAT(multi_read_exceeded
);
3718 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
3720 // Log current traffic stats
3721 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3722 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3723 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
3724 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
3725 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
3727 udp_tx
= udp_rx
= 0;
3728 udp_rx_pkt
= eth_rx_pkt
= 0;
3729 eth_tx
= eth_rx
= 0;
3732 if (config
->dump_speed
)
3733 printf("%s\n", config
->bandwidth
);
3735 // Update the internal time counter
3736 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3740 struct param_timer p
= { time_now
};
3741 run_plugins(PLUGIN_TIMER
, &p
);
3745 // Runs on every machine (master and slaves).
3746 if (next_cluster_ping
<= TIME
)
3748 // Check to see which of the cluster is still alive..
3750 cluster_send_ping(basetime
); // Only does anything if we're a slave
3751 cluster_check_master(); // ditto.
3753 cluster_heartbeat(); // Only does anything if we're a master.
3754 cluster_check_slaves(); // ditto.
3756 master_update_counts(); // If we're a slave, send our byte counters to our master.
3758 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
3759 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
3761 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
3764 if (!config
->cluster_iam_master
)
3767 // Run token bucket filtering queue..
3768 // Only run it every 1/10th of a second.
3770 static clockt last_run
= 0;
3771 if (last_run
!= TIME
)
3778 // Handle timeouts, retries etc.
3780 static double last_clean
= 0;
3784 TIME
= now(&this_clean
);
3785 diff
= this_clean
- last_clean
;
3787 // Run during idle time (after we've handled
3788 // all incoming packets) or every 1/10th sec
3789 if (!more
|| diff
> 0.1)
3791 regular_cleanups(diff
);
3792 last_clean
= this_clean
;
3796 if (*config
->accounting_dir
)
3798 static clockt next_acct
= 0;
3799 static clockt next_shut_acct
= 0;
3801 if (next_acct
<= TIME
)
3803 // Dump accounting data
3804 next_acct
= TIME
+ ACCT_TIME
;
3805 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3808 else if (next_shut_acct
<= TIME
)
3810 // Dump accounting data for shutdown sessions
3811 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3818 // Are we the master and shutting down??
3819 if (config
->cluster_iam_master
)
3820 cluster_heartbeat(); // Flush any queued changes..
3822 // Ok. Notify everyone we're shutting down. If we're
3823 // the master, this will force an election.
3824 cluster_send_ping(0);
3827 // Important!!! We MUST not process any packets past this point!
3828 LOG(1, 0, 0, "Shutdown complete\n");
3831 static void stripdomain(char *host
)
3835 if ((p
= strchr(host
, '.')))
3841 FILE *resolv
= fopen("/etc/resolv.conf", "r");
3847 while (fgets(buf
, sizeof(buf
), resolv
))
3849 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
3852 if (!isspace(buf
[6]))
3856 while (isspace(*b
)) b
++;
3861 while (*b
&& !isspace(*b
)) b
++;
3863 if (buf
[0] == 'd') // domain is canonical
3869 // first search line
3872 // hold, may be subsequent domain line
3873 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
3884 int hl
= strlen(host
);
3885 int dl
= strlen(domain
);
3886 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
3887 host
[hl
-dl
- 1] = 0;
3891 *p
= 0; // everything after first dot
3896 // Init data structures
3897 static void initdata(int optdebug
, char *optconfig
)
3901 if (!(config
= shared_malloc(sizeof(configt
))))
3903 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
3907 memset(config
, 0, sizeof(configt
));
3908 time(&config
->start_time
);
3909 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
3910 config
->debug
= optdebug
;
3911 config
->num_tbfs
= MAXTBFS
;
3912 config
->rl_rate
= 28; // 28kbps
3913 config
->cluster_mcast_ttl
= 1;
3914 config
->cluster_master_min_adv
= 1;
3915 config
->ppp_restart_time
= 3;
3916 config
->ppp_max_configure
= 10;
3917 config
->ppp_max_failure
= 5;
3918 strcpy(config
->random_device
, RANDOMDEVICE
);
3920 log_stream
= stderr
;
3923 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
3925 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
3928 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
3931 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
3933 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
3936 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
3938 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
3941 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
3943 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
3946 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
3948 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
3951 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
3953 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
3957 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
3959 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
3963 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
3965 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
3969 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
3971 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
3975 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
3977 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
3980 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
3982 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
3984 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
3987 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
3989 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
3991 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
3994 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
3996 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
3997 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
3998 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
3999 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4000 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4002 // Put all the sessions on the free list marked as undefined.
4003 for (i
= 1; i
< MAXSESSION
; i
++)
4005 session
[i
].next
= i
+ 1;
4006 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4008 session
[MAXSESSION
- 1].next
= 0;
4011 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4012 for (i
= 1; i
< MAXTUNNEL
; i
++)
4013 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4015 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4016 bundle
[i
].state
= BUNDLEUNDEF
;
4021 // Grab my hostname unless it's been specified
4022 gethostname(hostname
, sizeof(hostname
));
4023 stripdomain(hostname
);
4026 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4029 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4031 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4037 static int assign_ip_address(sessionidt s
)
4041 time_t best_time
= time_now
;
4042 char *u
= session
[s
].user
;
4046 CSTAT(assign_ip_address
);
4048 for (i
= 1; i
< ip_pool_size
; i
++)
4050 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4053 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4060 if (ip_address_pool
[i
].last
< best_time
)
4063 if (!(best_time
= ip_address_pool
[i
].last
))
4064 break; // never used, grab this one
4070 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4074 session
[s
].ip
= ip_address_pool
[best
].address
;
4075 session
[s
].ip_pool_index
= best
;
4076 ip_address_pool
[best
].assigned
= 1;
4077 ip_address_pool
[best
].last
= time_now
;
4078 ip_address_pool
[best
].session
= s
;
4079 if (session
[s
].walled_garden
)
4080 /* Don't track addresses of users in walled garden (note: this
4081 means that their address isn't "sticky" even if they get
4083 ip_address_pool
[best
].user
[0] = 0;
4085 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4088 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4089 reuse
? "Reusing" : "Allocating", best
);
4094 static void free_ip_address(sessionidt s
)
4096 int i
= session
[s
].ip_pool_index
;
4099 CSTAT(free_ip_address
);
4102 return; // what the?
4104 if (i
< 0) // Is this actually part of the ip pool?
4108 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4110 ip_address_pool
[i
].assigned
= 0;
4111 ip_address_pool
[i
].session
= 0;
4112 ip_address_pool
[i
].last
= time_now
;
4116 // Fsck the address pool against the session table.
4117 // Normally only called when we become a master.
4119 // This isn't perfect: We aren't keep tracking of which
4120 // users used to have an IP address.
4122 void rebuild_address_pool(void)
4127 // Zero the IP pool allocation, and build
4128 // a map from IP address to pool index.
4129 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4131 ip_address_pool
[i
].assigned
= 0;
4132 ip_address_pool
[i
].session
= 0;
4133 if (!ip_address_pool
[i
].address
)
4136 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4139 for (i
= 0; i
< MAXSESSION
; ++i
)
4142 if (!(session
[i
].opened
&& session
[i
].ip
))
4145 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4147 if (session
[i
].ip_pool_index
< 0)
4149 // Not allocated out of the pool.
4150 if (ipid
< 1) // Not found in the pool either? good.
4153 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4154 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4156 // Fall through and process it as part of the pool.
4160 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4162 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4164 session
[i
].ip_pool_index
= ipid
;
4168 ip_address_pool
[ipid
].assigned
= 1;
4169 ip_address_pool
[ipid
].session
= i
;
4170 ip_address_pool
[ipid
].last
= time_now
;
4171 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4172 session
[i
].ip_pool_index
= ipid
;
4173 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4178 // Fix the address pool to match a changed session.
4179 // (usually when the master sends us an update).
4180 static void fix_address_pool(int sid
)
4184 ipid
= session
[sid
].ip_pool_index
;
4186 if (ipid
> ip_pool_size
)
4187 return; // Ignore it. rebuild_address_pool will fix it up.
4189 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4190 return; // Just ignore it. rebuild_address_pool will take care of it.
4192 ip_address_pool
[ipid
].assigned
= 1;
4193 ip_address_pool
[ipid
].session
= sid
;
4194 ip_address_pool
[ipid
].last
= time_now
;
4195 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4199 // Add a block of addresses to the IP pool to hand out.
4201 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
4205 mask
= 0xffffffff; // Host route only.
4209 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4212 for (i
= addr
;(i
& mask
) == addr
; ++i
)
4214 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4215 continue; // Skip 0 and broadcast addresses.
4217 ip_address_pool
[ip_pool_size
].address
= i
;
4218 ip_address_pool
[ip_pool_size
].assigned
= 0;
4220 if (ip_pool_size
>= MAXIPPOOL
)
4222 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4228 // Initialize the IP address pool
4229 static void initippool()
4234 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4236 if (!(f
= fopen(IPPOOLFILE
, "r")))
4238 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4242 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4245 buf
[4095] = 0; // Force it to be zero terminated/
4247 if (*buf
== '#' || *buf
== '\n')
4248 continue; // Skip comments / blank lines
4249 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4250 if ((p
= (char *)strchr(buf
, ':')))
4254 src
= inet_addr(buf
);
4255 if (src
== INADDR_NONE
)
4257 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4260 // This entry is for a specific IP only
4261 if (src
!= config
->bind_address
)
4266 if ((p
= (char *)strchr(pool
, '/')))
4270 in_addr_t start
= 0, mask
= 0;
4272 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4274 if (!*p
|| !(numbits
= atoi(p
)))
4276 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4279 start
= ntohl(inet_addr(pool
));
4280 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
4282 // Add a static route for this pool
4283 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
4284 fmtaddr(htonl(start
), 0), 32 + mask
);
4286 routeset(0, start
, mask
, 0, 1);
4288 add_to_ip_pool(start
, mask
);
4292 // It's a single ip address
4293 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4297 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4300 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4302 struct sockaddr_in snoop_addr
= {0};
4303 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4306 snoop_addr
.sin_family
= AF_INET
;
4307 snoop_addr
.sin_addr
.s_addr
= destination
;
4308 snoop_addr
.sin_port
= ntohs(port
);
4310 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4311 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4312 htons(snoop_addr
.sin_port
));
4314 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4315 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4317 STAT(packets_snooped
);
4320 static int dump_session(FILE **f
, sessiont
*s
)
4322 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4327 char filename
[1024];
4329 time_t now
= time(NULL
);
4331 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4332 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4334 if (!(*f
= fopen(filename
, "w")))
4336 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4340 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4341 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4346 "# format: username ip qos uptxoctets downrxoctets\n",
4348 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4353 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4354 fprintf(*f
, "%s %s %d %u %u\n",
4355 s
->user
, // username
4356 fmtaddr(htonl(s
->ip
), 0), // ip
4357 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4358 (uint32_t) s
->cin_delta
, // uptxoctets
4359 (uint32_t) s
->cout_delta
); // downrxoctets
4361 s
->cin_delta
= s
->cout_delta
= 0;
4366 static void dump_acct_info(int all
)
4372 CSTAT(dump_acct_info
);
4376 for (i
= 0; i
< shut_acct_n
; i
++)
4377 dump_session(&f
, &shut_acct
[i
]);
4383 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4384 dump_session(&f
, &session
[i
]);
4391 int main(int argc
, char *argv
[])
4395 char *optconfig
= CONFIGFILE
;
4397 time(&basetime
); // start clock
4400 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4405 if (fork()) exit(0);
4407 freopen("/dev/null", "r", stdin
);
4408 freopen("/dev/null", "w", stdout
);
4409 freopen("/dev/null", "w", stderr
);
4418 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4421 printf("Args are:\n"
4422 "\t-d\t\tDetach from terminal\n"
4423 "\t-c <file>\tConfig file\n"
4424 "\t-h <hostname>\tForce hostname\n"
4432 // Start the timer routine off
4434 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4437 initdata(optdebug
, optconfig
);
4442 init_tbf(config
->num_tbfs
);
4444 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4445 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4446 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4449 rlim
.rlim_cur
= RLIM_INFINITY
;
4450 rlim
.rlim_max
= RLIM_INFINITY
;
4451 // Remove the maximum core size
4452 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4453 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4455 // Make core dumps go to /tmp
4459 if (config
->scheduler_fifo
)
4462 struct sched_param params
= {0};
4463 params
.sched_priority
= 1;
4465 if (get_nprocs() < 2)
4467 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4468 config
->scheduler_fifo
= 0;
4472 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4474 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4478 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4479 config
->scheduler_fifo
= 0;
4484 /* Set up the cluster communications port. */
4485 if (cluster_init() < 0)
4489 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4497 unsigned seed
= time_now
^ getpid();
4498 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4502 signal(SIGHUP
, sighup_handler
);
4503 signal(SIGCHLD
, sigchild_handler
);
4504 signal(SIGTERM
, shutdown_handler
);
4505 signal(SIGINT
, shutdown_handler
);
4506 signal(SIGQUIT
, shutdown_handler
);
4508 // Prevent us from getting paged out
4509 if (config
->lock_pages
)
4511 if (!mlockall(MCL_CURRENT
))
4512 LOG(1, 0, 0, "Locking pages into memory\n");
4514 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4519 /* remove plugins (so cleanup code gets run) */
4522 // Remove the PID file if we wrote it
4523 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4524 unlink(config
->pid_file
);
4526 /* kill CLI children */
4527 signal(SIGTERM
, SIG_IGN
);
4532 static void sighup_handler(int sig
)
4537 static void shutdown_handler(int sig
)
4539 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4542 static void sigchild_handler(int sig
)
4544 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4548 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4551 *challenge_response
= NULL
;
4553 if (!*config
->l2tp_secret
)
4555 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4559 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4561 *challenge_response
= calloc(17, 1);
4564 MD5_Update(&ctx
, &id
, 1);
4565 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4566 MD5_Update(&ctx
, challenge
, challenge_length
);
4567 MD5_Final(*challenge_response
, &ctx
);
4572 static int facility_value(char *name
)
4575 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4577 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4578 return facilitynames
[i
].c_val
;
4583 static void update_config()
4587 static int timeout
= 0;
4588 static int interval
= 0;
4595 if (log_stream
!= stderr
)
4601 if (*config
->log_filename
)
4603 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4605 char *p
= config
->log_filename
+ 7;
4608 openlog("l2tpns", LOG_PID
, facility_value(p
));
4612 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4614 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4616 fseek(log_stream
, 0, SEEK_END
);
4617 setbuf(log_stream
, NULL
);
4621 log_stream
= stderr
;
4622 setbuf(log_stream
, NULL
);
4628 log_stream
= stderr
;
4629 setbuf(log_stream
, NULL
);
4632 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4633 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4635 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4636 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4637 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4639 // reset MRU/MSS globals
4640 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4641 if (MRU
> PPPoE_MRU
)
4644 MSS
= MRU
- TCP_HDRS
;
4647 config
->numradiusservers
= 0;
4648 for (i
= 0; i
< MAXRADSERVER
; i
++)
4649 if (config
->radiusserver
[i
])
4651 config
->numradiusservers
++;
4652 // Set radius port: if not set, take the port from the
4653 // first radius server. For the first radius server,
4654 // take the #defined default value from l2tpns.h
4656 // test twice, In case someone works with
4657 // a secondary radius server without defining
4658 // a primary one, this will work even then.
4659 if (i
> 0 && !config
->radiusport
[i
])
4660 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4661 if (!config
->radiusport
[i
])
4662 config
->radiusport
[i
] = RADPORT
;
4665 if (!config
->numradiusservers
)
4666 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4668 // parse radius_authtypes_s
4669 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4670 p
= config
->radius_authtypes_s
;
4673 char *s
= strpbrk(p
, " \t,");
4679 while (*s
== ' ' || *s
== '\t')
4686 if (!strncasecmp("chap", p
, strlen(p
)))
4688 else if (!strncasecmp("pap", p
, strlen(p
)))
4691 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4693 config
->radius_authtypes
|= type
;
4694 if (!config
->radius_authprefer
)
4695 config
->radius_authprefer
= type
;
4700 if (!config
->radius_authtypes
)
4702 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4703 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4706 // normalise radius_authtypes_s
4707 if (config
->radius_authprefer
== AUTHPAP
)
4709 strcpy(config
->radius_authtypes_s
, "pap");
4710 if (config
->radius_authtypes
& AUTHCHAP
)
4711 strcat(config
->radius_authtypes_s
, ", chap");
4715 strcpy(config
->radius_authtypes_s
, "chap");
4716 if (config
->radius_authtypes
& AUTHPAP
)
4717 strcat(config
->radius_authtypes_s
, ", pap");
4720 if (!config
->radius_dae_port
)
4721 config
->radius_dae_port
= DAEPORT
;
4723 // re-initialise the random number source
4724 initrandom(config
->random_device
);
4727 for (i
= 0; i
< MAXPLUGINS
; i
++)
4729 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
4732 if (*config
->plugins
[i
])
4735 add_plugin(config
->plugins
[i
]);
4737 else if (*config
->old_plugins
[i
])
4740 remove_plugin(config
->old_plugins
[i
]);
4744 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
4745 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
4746 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
4747 if (!*config
->cluster_interface
)
4748 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
4750 if (!config
->cluster_hb_interval
)
4751 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
4753 if (!config
->cluster_hb_timeout
)
4754 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
4756 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
4758 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
4759 // late, ensure we're sufficiently larger than that
4760 int t
= 4 * config
->cluster_hb_interval
+ 11;
4762 if (config
->cluster_hb_timeout
< t
)
4764 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
4765 config
->cluster_hb_timeout
= t
;
4768 // Push timing changes to the slaves immediately if we're the master
4769 if (config
->cluster_iam_master
)
4770 cluster_heartbeat();
4772 interval
= config
->cluster_hb_interval
;
4773 timeout
= config
->cluster_hb_timeout
;
4777 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
4780 if ((f
= fopen(config
->pid_file
, "w")))
4782 fprintf(f
, "%d\n", getpid());
4784 config
->wrote_pid
= 1;
4788 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
4793 static void read_config_file()
4797 if (!config
->config_file
) return;
4798 if (!(f
= fopen(config
->config_file
, "r")))
4800 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
4804 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
4806 LOG(3, 0, 0, "Done reading config file\n");
4810 int sessionsetup(sessionidt s
, tunnelidt t
)
4812 // A session now exists, set it up
4818 CSTAT(sessionsetup
);
4820 LOG(3, s
, t
, "Doing session setup for session\n");
4824 assign_ip_address(s
);
4827 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
4828 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
4831 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
4832 fmtaddr(htonl(session
[s
].ip
), 0));
4836 // Make sure this is right
4837 session
[s
].tunnel
= t
;
4839 // Join a bundle if the MRRU option is accepted
4840 if (session
[s
].mrru
> 0 && !session
[s
].bundle
)
4842 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
4844 cluster_send_bundle(session
[s
].bundle
);
4847 // zap old sessions with same IP and/or username
4848 // Don't kill gardened sessions - doing so leads to a DoS
4849 // from someone who doesn't need to know the password
4852 user
= session
[s
].user
;
4853 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4855 if (i
== s
) continue;
4856 if (!session
[s
].opened
) continue;
4857 if (ip
== session
[i
].ip
)
4859 sessionkill(i
, "Duplicate IP address");
4863 if (config
->allow_duplicate_users
)
4866 if (session
[s
].walled_garden
|| session
[i
].walled_garden
)
4869 // Allow duplicate sessions for guest account.
4870 if (*config
->guest_user
&& !strcasecmp(user
, config
->guest_user
))
4873 // Allow duplicate sessions for multilink ones of the same bundle.
4874 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
4877 // Drop the new session in case of duplicate sessionss, not the old one.
4878 if (!strcasecmp(user
, session
[i
].user
))
4879 sessionkill(i
, "Duplicate session for users");
4886 // Add the route for this session.
4887 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
4889 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
4890 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
4893 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
4896 // Static IPs need to be routed if not already
4897 // convered by a Framed-Route. Anything else is part
4898 // of the IP address pool and is already routed, it
4899 // just needs to be added to the IP cache.
4900 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
4901 if (session
[s
].ip_pool_index
== -1) // static ip
4903 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
4906 cache_ipmap(session
[s
].ip
, s
);
4909 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
4910 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
4912 // Run the plugin's against this new session.
4914 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
4915 run_plugins(PLUGIN_NEW_SESSION
, &data
);
4918 // Allocate TBFs if throttled
4919 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
4920 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
4922 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
4924 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
4925 fmtaddr(htonl(session
[s
].ip
), 0),
4926 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
4928 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
4930 return 1; // RADIUS OK and IP allocated, done...
4934 // This session just got dropped on us by the master or something.
4935 // Make sure our tables up up to date...
4937 int load_session(sessionidt s
, sessiont
*new)
4943 if (new->ip_pool_index
>= MAXIPPOOL
||
4944 new->tunnel
>= MAXTUNNEL
)
4946 LOG(0, s
, 0, "Strange session update received!\n");
4947 // FIXME! What to do here?
4952 // Ok. All sanity checks passed. Now we're committed to
4953 // loading the new session.
4956 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
4958 // See if routes/ip cache need updating
4959 if (new->ip
!= session
[s
].ip
)
4962 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
4963 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
4964 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
4972 // remove old routes...
4973 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
4975 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
4976 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
4979 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
4985 if (session
[s
].ip_pool_index
== -1) // static IP
4987 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
4989 else // It's part of the IP pool, remove it manually.
4990 uncache_ipmap(session
[s
].ip
);
4995 // add new routes...
4996 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
4998 if ((new->ip
& new->route
[i
].mask
) ==
4999 (new->route
[i
].ip
& new->route
[i
].mask
))
5002 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
5008 // If there's a new one, add it.
5009 if (new->ip_pool_index
== -1)
5011 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5014 cache_ipmap(new->ip
, s
);
5019 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5020 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5023 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5025 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5029 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5031 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5032 new->filter_out
= 0;
5035 if (new->filter_in
!= session
[s
].filter_in
)
5037 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5038 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5041 if (new->filter_out
!= session
[s
].filter_out
)
5043 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5044 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5047 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5048 // for walking the sessions to forward byte counts to the master.
5049 config
->cluster_highest_sessionid
= s
;
5051 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5053 // Do fixups into address pool.
5054 if (new->ip_pool_index
!= -1)
5055 fix_address_pool(s
);
5060 static void initplugins()
5064 loaded_plugins
= ll_init();
5065 // Initialize the plugins to nothing
5066 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5067 plugins
[i
] = ll_init();
5070 static void *open_plugin(char *plugin_name
, int load
)
5072 char path
[256] = "";
5074 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5075 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5076 return dlopen(path
, RTLD_NOW
);
5079 // plugin callback to get a config value
5080 static void *getconfig(char *key
, enum config_typet type
)
5084 for (i
= 0; config_values
[i
].key
; i
++)
5086 if (!strcmp(config_values
[i
].key
, key
))
5088 if (config_values
[i
].type
== type
)
5089 return ((void *) config
) + config_values
[i
].offset
;
5091 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5092 key
, type
, config_values
[i
].type
);
5098 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5102 static int add_plugin(char *plugin_name
)
5104 static struct pluginfuncs funcs
= {
5109 sessiontbysessionidt
,
5110 sessionidtbysessiont
,
5117 cluster_send_session
,
5120 void *p
= open_plugin(plugin_name
, 1);
5121 int (*initfunc
)(struct pluginfuncs
*);
5126 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5130 if (ll_contains(loaded_plugins
, p
))
5133 return 0; // already loaded
5137 int *v
= dlsym(p
, "plugin_api_version");
5138 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5140 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5146 if ((initfunc
= dlsym(p
, "plugin_init")))
5148 if (!initfunc(&funcs
))
5150 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5156 ll_push(loaded_plugins
, p
);
5158 for (i
= 0; i
< max_plugin_functions
; i
++)
5161 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5163 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5164 ll_push(plugins
[i
], x
);
5168 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5172 static void run_plugin_done(void *plugin
)
5174 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5180 static int remove_plugin(char *plugin_name
)
5182 void *p
= open_plugin(plugin_name
, 0);
5188 if (ll_contains(loaded_plugins
, p
))
5191 for (i
= 0; i
< max_plugin_functions
; i
++)
5194 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5195 ll_delete(plugins
[i
], x
);
5198 ll_delete(loaded_plugins
, p
);
5204 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5208 int run_plugins(int plugin_type
, void *data
)
5210 int (*func
)(void *data
);
5212 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5213 return PLUGIN_RET_ERROR
;
5215 ll_reset(plugins
[plugin_type
]);
5216 while ((func
= ll_next(plugins
[plugin_type
])))
5220 if (r
!= PLUGIN_RET_OK
)
5221 return r
; // stop here
5224 return PLUGIN_RET_OK
;
5227 static void plugins_done()
5231 ll_reset(loaded_plugins
);
5232 while ((p
= ll_next(loaded_plugins
)))
5236 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5238 struct nsctl request
;
5239 struct nsctl response
;
5240 int type
= unpack_control(&request
, buf
, len
);
5244 if (log_stream
&& config
->debug
>= 4)
5248 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5249 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5253 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5254 dump_control(&request
, log_stream
);
5260 case NSCTL_REQ_LOAD
:
5261 if (request
.argc
!= 1)
5263 response
.type
= NSCTL_RES_ERR
;
5265 response
.argv
[0] = "name of plugin required";
5267 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5269 response
.type
= NSCTL_RES_ERR
;
5271 response
.argv
[0] = !r
5272 ? "plugin already loaded"
5273 : "error loading plugin";
5277 response
.type
= NSCTL_RES_OK
;
5283 case NSCTL_REQ_UNLOAD
:
5284 if (request
.argc
!= 1)
5286 response
.type
= NSCTL_RES_ERR
;
5288 response
.argv
[0] = "name of plugin required";
5290 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5292 response
.type
= NSCTL_RES_ERR
;
5294 response
.argv
[0] = !r
5295 ? "plugin not loaded"
5296 : "plugin not found";
5300 response
.type
= NSCTL_RES_OK
;
5306 case NSCTL_REQ_HELP
:
5307 response
.type
= NSCTL_RES_OK
;
5310 ll_reset(loaded_plugins
);
5311 while ((p
= ll_next(loaded_plugins
)))
5313 char **help
= dlsym(p
, "plugin_control_help");
5314 while (response
.argc
< 0xff && help
&& *help
)
5315 response
.argv
[response
.argc
++] = *help
++;
5320 case NSCTL_REQ_CONTROL
:
5322 struct param_control param
= {
5323 config
->cluster_iam_master
,
5330 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5332 if (r
== PLUGIN_RET_ERROR
)
5334 response
.type
= NSCTL_RES_ERR
;
5336 response
.argv
[0] = param
.additional
5338 : "error returned by plugin";
5340 else if (r
== PLUGIN_RET_NOTMASTER
)
5342 static char msg
[] = "must be run on master: 000.000.000.000";
5344 response
.type
= NSCTL_RES_ERR
;
5346 if (config
->cluster_master_address
)
5348 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5349 response
.argv
[0] = msg
;
5353 response
.argv
[0] = "must be run on master: none elected";
5356 else if (!(param
.response
& NSCTL_RESPONSE
))
5358 response
.type
= NSCTL_RES_ERR
;
5360 response
.argv
[0] = param
.response
5361 ? "unrecognised response value from plugin"
5362 : "unhandled action";
5366 response
.type
= param
.response
;
5368 if (param
.additional
)
5371 response
.argv
[0] = param
.additional
;
5379 response
.type
= NSCTL_RES_ERR
;
5381 response
.argv
[0] = "error unpacking control packet";
5384 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5387 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5391 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5394 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5395 if (log_stream
&& config
->debug
>= 4)
5397 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5398 dump_control(&response
, log_stream
);
5402 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5403 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5408 static tunnelidt
new_tunnel()
5411 for (i
= 1; i
< MAXTUNNEL
; i
++)
5413 if (tunnel
[i
].state
== TUNNELFREE
)
5415 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5416 if (i
> config
->cluster_highest_tunnelid
)
5417 config
->cluster_highest_tunnelid
= i
;
5421 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5426 // We're becoming the master. Do any required setup..
5428 // This is principally telling all the plugins that we're
5429 // now a master, and telling them about all the sessions
5430 // that are active too..
5432 void become_master(void)
5435 static struct event_data d
[RADIUS_FDS
];
5436 struct epoll_event e
;
5438 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5440 // running a bunch of iptables commands is slow and can cause
5441 // the master to drop tunnels on takeover--kludge around the
5442 // problem by forking for the moment (note: race)
5443 if (!fork_and_close())
5445 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5447 if (!session
[s
].opened
) // Not an in-use session.
5450 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5457 for (i
= 0; i
< RADIUS_FDS
; i
++)
5459 d
[i
].type
= FD_TYPE_RADIUS
;
5463 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5467 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5473 if (CLI_HELP_REQUESTED
)
5474 return CLI_HELP_NO_ARGS
;
5477 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5479 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5482 if (!session
[s
].opened
)
5485 idle
= time_now
- session
[s
].last_data
;
5486 idle
/= 5 ; // In multiples of 5 seconds.
5496 for (i
= 0; i
< 63; ++i
)
5498 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5500 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5501 cli_print(cli
, "%d total sessions open.", count
);
5505 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5511 if (CLI_HELP_REQUESTED
)
5512 return CLI_HELP_NO_ARGS
;
5515 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5517 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5520 if (!session
[s
].opened
)
5523 d
= time_now
- session
[s
].opened
;
5526 while (d
> 1 && open
< 32)
5536 for (i
= 0; i
< 30; ++i
)
5538 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5541 cli_print(cli
, "%d total sessions open.", count
);
5547 * This unencodes the AVP using the L2TP secret and the previously
5548 * stored random vector. It overwrites the hidden data with the
5549 * unhidden AVP subformat.
5551 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5557 uint16_t m
= htons(type
);
5559 // Compute initial pad
5561 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5562 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5563 MD5_Update(&ctx
, vector
, vec_len
);
5564 MD5_Final(digest
, &ctx
);
5566 // pointer to last decoded 16 octets
5571 // calculate a new pad based on the last decoded block
5572 if (d
>= sizeof(digest
))
5575 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5576 MD5_Update(&ctx
, last
, sizeof(digest
));
5577 MD5_Final(digest
, &ctx
);
5583 *value
++ ^= digest
[d
++];
5588 int find_filter(char const *name
, size_t len
)
5593 for (i
= 0; i
< MAXFILTER
; i
++)
5595 if (!*ip_filters
[i
].name
)
5603 if (strlen(ip_filters
[i
].name
) != len
)
5606 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5613 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5617 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5618 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5619 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5620 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5621 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5627 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5631 case FILTER_FLAG_OP_ANY
:
5632 return (flags
& sflags
) || (~flags
& cflags
);
5634 case FILTER_FLAG_OP_ALL
:
5635 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5637 case FILTER_FLAG_OP_EST
:
5638 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5644 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5646 uint16_t frag_offset
;
5650 uint16_t src_port
= 0;
5651 uint16_t dst_port
= 0;
5653 ip_filter_rulet
*rule
;
5655 if (len
< 20) // up to end of destination address
5658 if ((*buf
>> 4) != 4) // IPv4
5661 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5663 src_ip
= *(in_addr_t
*) (buf
+ 12);
5664 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5666 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5668 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5669 if (len
< l
+ 4) // ports
5672 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
5673 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
5674 if (proto
== IPPROTO_TCP
)
5676 if (len
< l
+ 14) // flags
5679 flags
= buf
[l
+ 13] & 0x3f;
5683 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
5685 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
5688 if (rule
->src_wild
!= INADDR_BROADCAST
&&
5689 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
5692 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
5693 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
5698 // layer 4 deny rules are skipped
5699 if (rule
->action
== FILTER_ACTION_DENY
&&
5700 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
5708 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
5710 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
5713 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
5716 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
5717 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
5724 return rule
->action
== FILTER_ACTION_PERMIT
;