3 // Copyright (c) 2003, 2004, 2005 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.107 2005/06/02 11:32:30 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 snoopfd
= -1; // UDP file handle for sending out intercept data
64 int *radfds
= NULL
; // RADIUS requests file handles
65 int ifrfd
= -1; // File descriptor for routing, etc
66 int ifr6fd
= -1; // File descriptor for IPv6 routing, etc
67 static int rand_fd
= -1; // Random data source
68 time_t basetime
= 0; // base clock
69 char hostname
[1000] = ""; // us.
70 static int tunidx
; // ifr_ifindex of tun device
71 static int syslog_log
= 0; // are we logging to syslog
72 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
73 extern int cluster_sockfd
; // Intra-cluster communications socket.
74 uint32_t last_id
= 0; // Unique ID for radius accounting
76 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
77 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
79 static void *ip_hash
[256]; // Mapping from IP address to session structures.
82 struct ipv6radix
*branch
;
83 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
86 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
87 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
90 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
91 time_t time_now
= 0; // Current time in seconds since epoch.
92 static char time_now_string
[64] = {0}; // Current time as a string.
93 char main_quit
= 0; // True if we're in the process of exiting.
94 linked_list
*loaded_plugins
;
95 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
97 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
98 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
100 config_descriptt config_values
[] = {
101 CONFIG("debug", debug
, INT
),
102 CONFIG("log_file", log_filename
, STRING
),
103 CONFIG("pid_file", pid_file
, STRING
),
104 CONFIG("random_device", random_device
, STRING
),
105 CONFIG("l2tp_secret", l2tpsecret
, STRING
),
106 CONFIG("primary_dns", default_dns1
, IPv4
),
107 CONFIG("secondary_dns", default_dns2
, IPv4
),
108 CONFIG("primary_radius", radiusserver
[0], IPv4
),
109 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
110 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
111 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
112 CONFIG("radius_accounting", radius_accounting
, BOOL
),
113 CONFIG("radius_interim", radius_interim
, INT
),
114 CONFIG("radius_secret", radiussecret
, STRING
),
115 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
116 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
117 CONFIG("bind_address", bind_address
, IPv4
),
118 CONFIG("peer_address", peer_address
, IPv4
),
119 CONFIG("send_garp", send_garp
, BOOL
),
120 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
121 CONFIG("throttle_buckets", num_tbfs
, INT
),
122 CONFIG("accounting_dir", accounting_dir
, STRING
),
123 CONFIG("setuid", target_uid
, INT
),
124 CONFIG("dump_speed", dump_speed
, BOOL
),
125 CONFIG("multi_read_count", multi_read_count
, INT
),
126 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
127 CONFIG("lock_pages", lock_pages
, BOOL
),
128 CONFIG("icmp_rate", icmp_rate
, INT
),
129 CONFIG("packet_limit", max_packets
, INT
),
130 CONFIG("cluster_address", cluster_address
, IPv4
),
131 CONFIG("cluster_interface", cluster_interface
, STRING
),
132 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
133 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
134 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
135 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
139 static char *plugin_functions
[] = {
146 "plugin_new_session",
147 "plugin_kill_session",
149 "plugin_radius_response",
150 "plugin_become_master",
151 "plugin_new_session_master",
154 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
156 // Counters for shutdown sessions
157 static sessiont shut_acct
[8192];
158 static sessionidt shut_acct_n
= 0;
160 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
161 sessiont
*session
= NULL
; // Array of session structures.
162 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
163 radiust
*radius
= NULL
; // Array of radius structures.
164 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
165 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
166 static controlt
*controlfree
= 0;
167 struct Tstats
*_statistics
= NULL
;
169 struct Tringbuffer
*ringbuffer
= NULL
;
172 static void cache_ipmap(in_addr_t ip
, int s
);
173 static void uncache_ipmap(in_addr_t ip
);
174 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, int s
);
175 static void free_ip_address(sessionidt s
);
176 static void dump_acct_info(int all
);
177 static void sighup_handler(int sig
);
178 static void sigalrm_handler(int sig
);
179 static void sigterm_handler(int sig
);
180 static void sigquit_handler(int sig
);
181 static void sigchild_handler(int sig
);
182 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
);
183 static void update_config(void);
184 static void read_config_file(void);
185 static void initplugins(void);
186 static int add_plugin(char *plugin_name
);
187 static int remove_plugin(char *plugin_name
);
188 static void plugins_done(void);
189 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
);
190 static tunnelidt
new_tunnel(void);
191 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
193 // on slaves, alow BGP to withdraw cleanly before exiting
196 // return internal time (10ths since process startup), set f if given
197 static clockt
now(double *f
)
201 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
202 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
205 // work out a retry time based on try number
206 // This is a straight bounded exponential backoff.
207 // Maximum re-try time is 32 seconds. (2^5).
208 clockt
backoff(uint8_t try)
210 if (try > 5) try = 5; // max backoff
211 return now(NULL
) + 10 * (1 << try);
216 // Log a debug message. Typically called via the LOG macro
218 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
220 static char message
[65536] = {0};
226 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
227 ringbuffer
->tail
= 0;
228 if (ringbuffer
->tail
== ringbuffer
->head
)
229 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
230 ringbuffer
->head
= 0;
232 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
233 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
234 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
235 va_start(ap
, format
);
236 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
241 if (config
->debug
< level
) return;
243 va_start(ap
, format
);
244 vsnprintf(message
, sizeof(message
), format
, ap
);
247 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
249 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
254 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
257 const uint8_t *d
= (const uint8_t *) data
;
259 if (config
->debug
< level
) return;
261 // No support for _log_hex to syslog
264 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
265 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
267 for (i
= 0; i
< maxsize
; )
269 fprintf(log_stream
, "%4X: ", i
);
270 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
272 fprintf(log_stream
, "%02X ", d
[j
]);
274 fputs(": ", log_stream
);
277 for (; j
< i
+ 16; j
++)
279 fputs(" ", log_stream
);
281 fputs(": ", log_stream
);
284 fputs(" ", log_stream
);
285 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
287 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
288 fputc(d
[j
], log_stream
);
290 fputc('.', log_stream
);
293 fputs(" ", log_stream
);
297 fputs("\n", log_stream
);
301 setbuf(log_stream
, NULL
);
305 // update a counter, accumulating 2^32 wraps
306 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
308 uint32_t new = *counter
+ delta
;
315 // initialise the random generator
316 static void initrandom(char *source
)
318 static char path
[sizeof(config
->random_device
)] = "*undefined*";
320 // reinitialise only if we are forced to do so or if the config has changed
321 if (source
&& !strncmp(path
, source
, sizeof(path
)))
324 // close previous source, if any
325 if (rand_fd
>= 0) close(rand_fd
);
332 snprintf(path
, sizeof(path
), "%s", source
);
336 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
338 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
339 path
, strerror(errno
));
343 // no source: seed prng
345 unsigned seed
= time_now
^ getpid();
346 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
351 // fill buffer with random data
352 void random_data(uint8_t *buf
, int len
)
359 n
= read(rand_fd
, buf
, len
);
360 if (n
>= len
) return;
365 LOG(0, 0, 0, "Error reading from random source: %s\n",
368 // fall back to rand()
376 // append missing data
378 // not using the low order bits from the prng stream
379 buf
[n
++] = (rand() >> 4) & 0xff;
384 // This adds it to the routing table, advertises it
385 // via BGP if enabled, and stuffs it into the
386 // 'sessionbyip' cache.
388 // 'ip' and 'mask' must be in _host_ order.
390 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
395 if (!mask
) mask
= 0xffffffff;
397 ip
&= mask
; // Force the ip to be the first one in the route.
399 memset(&r
, 0, sizeof(r
));
400 r
.rt_dev
= config
->tundevice
;
401 r
.rt_dst
.sa_family
= AF_INET
;
402 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
403 r
.rt_gateway
.sa_family
= AF_INET
;
404 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
405 r
.rt_genmask
.sa_family
= AF_INET
;
406 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
407 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
409 r
.rt_flags
|= RTF_GATEWAY
;
410 else if (mask
== 0xffffffff)
411 r
.rt_flags
|= RTF_HOST
;
413 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
414 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
415 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
417 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
418 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
422 bgp_add_route(htonl(ip
), htonl(mask
));
424 bgp_del_route(htonl(ip
), htonl(mask
));
427 // Add/Remove the IPs to the 'sessionbyip' cache.
428 // Note that we add the zero address in the case of
429 // a network route. Roll on CIDR.
431 // Note that 's == 0' implies this is the address pool.
432 // We still cache it here, because it will pre-fill
433 // the malloc'ed tree.
437 if (!add
) // Are we deleting a route?
438 s
= 0; // Caching the session as '0' is the same as uncaching.
440 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
445 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
448 char ipv6addr
[INET6_ADDRSTRLEN
];
452 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
456 memset(&rt
, 0, sizeof(rt
));
458 memcpy(&rt
.rtmsg_dst
, &ip
, sizeof(struct in6_addr
));
459 rt
.rtmsg_dst_len
= prefixlen
;
461 rt
.rtmsg_flags
= RTF_UP
;
462 rt
.rtmsg_ifindex
= tunidx
;
464 LOG(1, 0, 0, "Route %s %s/%d\n",
466 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
469 if (ioctl(ifr6fd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &rt
) < 0)
470 LOG(0, 0, 0, "route6set() error in ioctl: %s\n",
473 // FIXME: need to add BGP routing (RFC2858)
477 if (!add
) // Are we deleting a route?
478 s
= 0; // Caching the session as '0' is the same as uncaching.
480 cache_ipv6map(ip
, prefixlen
, s
);
486 // defined in linux/ipv6.h, but tricky to include from user-space
487 // TODO: move routing to use netlink rather than ioctl
489 struct in6_addr ifr6_addr
;
490 __u32 ifr6_prefixlen
;
491 unsigned int ifr6_ifindex
;
495 // Set up TUN interface
496 static void inittun(void)
499 struct in6_ifreq ifr6
;
500 struct sockaddr_in sin
= {0};
501 memset(&ifr
, 0, sizeof(ifr
));
502 ifr
.ifr_flags
= IFF_TUN
;
504 tunfd
= open(TUNDEVICE
, O_RDWR
);
507 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
511 int flags
= fcntl(tunfd
, F_GETFL
, 0);
512 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
514 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
516 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
519 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
520 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
521 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
523 sin
.sin_family
= AF_INET
;
524 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
525 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
527 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
529 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
532 /* Bump up the qlen to deal with bursts from the network */
534 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
536 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
539 ifr
.ifr_flags
= IFF_UP
;
540 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
542 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
545 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
547 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno
));
550 tunidx
= ifr
.ifr_ifindex
;
552 // Only setup IPv6 on the tun device if we have a configured prefix
553 if (config
->ipv6_prefix
.s6_addr
[0] > 0) {
554 ifr6fd
= socket(PF_INET6
, SOCK_DGRAM
, 0);
556 // Link local address is FE80::1
557 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
558 ifr6
.ifr6_addr
.s6_addr
[0] = 0xFE;
559 ifr6
.ifr6_addr
.s6_addr
[1] = 0x80;
560 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
561 ifr6
.ifr6_prefixlen
= 64;
562 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
563 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
565 LOG(0, 0, 0, "Error setting tun IPv6 link local address:"
566 " %s\n", strerror(errno
));
569 // Global address is prefix::1
570 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
571 ifr6
.ifr6_addr
= config
->ipv6_prefix
;
572 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
573 ifr6
.ifr6_prefixlen
= 64;
574 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
575 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
577 LOG(0, 0, 0, "Error setting tun IPv6 global address: %s\n",
584 static void initudp(void)
587 struct sockaddr_in addr
;
590 memset(&addr
, 0, sizeof(addr
));
591 addr
.sin_family
= AF_INET
;
592 addr
.sin_port
= htons(L2TPPORT
);
593 addr
.sin_addr
.s_addr
= config
->bind_address
;
594 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
595 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
597 int flags
= fcntl(udpfd
, F_GETFL
, 0);
598 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
600 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
602 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
605 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
608 memset(&addr
, 0, sizeof(addr
));
609 addr
.sin_family
= AF_INET
;
610 addr
.sin_port
= htons(NSCTL_PORT
);
611 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
612 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
613 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
615 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
621 // Find session by IP, < 1 for not found
623 // Confusingly enough, this 'ip' must be
624 // in _network_ order. This being the common
625 // case when looking it up from IP packet headers.
627 // We actually use this cache for two things.
628 // #1. For used IP addresses, this maps to the
629 // session ID that it's used by.
630 // #2. For un-used IP addresses, this maps to the
631 // index into the pool table that contains that
635 static int lookup_ipmap(in_addr_t ip
)
637 uint8_t *a
= (uint8_t *) &ip
;
638 uint8_t **d
= (uint8_t **) ip_hash
;
640 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
641 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
642 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
644 return (int) (intptr_t) d
[(size_t) *a
];
647 static int lookup_ipv6map(struct in6_addr ip
)
649 struct ipv6radix
*curnode
;
652 char ipv6addr
[INET6_ADDRSTRLEN
];
654 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
658 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
660 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
665 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
666 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
673 sessionidt
sessionbyip(in_addr_t ip
)
675 int s
= lookup_ipmap(ip
);
678 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
679 return (sessionidt
) s
;
684 sessionidt
sessionbyipv6(struct in6_addr ip
)
687 CSTAT(sessionbyipv6
);
689 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
690 (ip
.s6_addr
[0] == 0xFE && ip
.s6_addr
[1] == 0x80 &&
691 (ip
.s6_addr16
[1] == ip
.s6_addr16
[2] == ip
.s6_addr16
[3] == 0))) {
692 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
694 s
= lookup_ipv6map(ip
);
697 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
704 // Take an IP address in HOST byte order and
705 // add it to the sessionid by IP cache.
707 // (It's actually cached in network order)
709 static void cache_ipmap(in_addr_t ip
, int s
)
711 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
712 uint8_t *a
= (uint8_t *) &nip
;
713 uint8_t **d
= (uint8_t **) ip_hash
;
716 for (i
= 0; i
< 3; i
++)
718 if (!d
[(size_t) a
[i
]])
720 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof(void *))))
724 d
= (uint8_t **) d
[(size_t) a
[i
]];
727 d
[(size_t) a
[3]] = (uint8_t *) (intptr_t) s
;
730 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
733 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
734 // else a map to an ip pool index.
737 static void uncache_ipmap(in_addr_t ip
)
739 cache_ipmap(ip
, 0); // Assign it to the NULL session.
742 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, int s
)
746 struct ipv6radix
*curnode
;
747 char ipv6addr
[INET6_ADDRSTRLEN
];
749 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
751 bytes
= prefixlen
>> 3;
754 if (curnode
->branch
== NULL
)
756 if (!(curnode
->branch
= calloc(256,
757 sizeof (struct ipv6radix
))))
760 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
767 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
768 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
772 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
773 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
779 // CLI list to dump current ipcache.
781 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
783 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
787 if (CLI_HELP_REQUESTED
)
788 return CLI_HELP_NO_ARGS
;
790 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
792 for (i
= 0; i
< 256; ++i
)
797 for (j
= 0; j
< 256; ++j
)
802 for (k
= 0; k
< 256; ++k
)
807 for (l
= 0; l
< 256; ++l
)
811 cli_print(cli
, "%7d %d.%d.%d.%d", (int) (intptr_t) g
[l
], i
, j
, k
, l
);
817 cli_print(cli
, "%d entries in cache", count
);
822 // Find session by username, 0 for not found
823 // walled garden users aren't authenticated, so the username is
824 // reasonably useless. Ignore them to avoid incorrect actions
826 // This is VERY inefficent. Don't call it often. :)
828 sessionidt
sessionbyuser(char *username
)
831 CSTAT(sessionbyuser
);
833 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
835 if (!session
[s
].opened
)
838 if (session
[s
].walled_garden
)
839 continue; // Skip walled garden users.
841 if (!strncmp(session
[s
].user
, username
, 128))
845 return 0; // Not found.
848 void send_garp(in_addr_t ip
)
854 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
857 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
860 memset(&ifr
, 0, sizeof(ifr
));
861 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
862 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
864 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
868 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
869 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
871 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
876 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
879 static sessiont
*sessiontbysessionidt(sessionidt s
)
881 if (!s
|| s
>= MAXSESSION
) return NULL
;
885 static sessionidt
sessionidtbysessiont(sessiont
*s
)
887 sessionidt val
= s
-session
;
888 if (s
< session
|| val
>= MAXSESSION
) return 0;
892 // actually send a control message for a specific tunnel
893 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
895 struct sockaddr_in addr
;
901 static int backtrace_count
= 0;
902 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
903 STAT(tunnel_tx_errors
);
904 log_backtrace(backtrace_count
, 5)
910 static int backtrace_count
= 0;
911 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
912 log_backtrace(backtrace_count
, 5)
913 STAT(tunnel_tx_errors
);
917 memset(&addr
, 0, sizeof(addr
));
918 addr
.sin_family
= AF_INET
;
919 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
920 addr
.sin_port
= htons(tunnel
[t
].port
);
922 // sequence expected, if sequence in message
923 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
925 // If this is a control message, deal with retries
928 tunnel
[t
].last
= time_now
; // control message sent
929 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
930 if (tunnel
[t
].try > 1)
932 STAT(tunnel_retries
);
933 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
937 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
939 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
940 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
941 STAT(tunnel_tx_errors
);
945 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
946 STAT(tunnel_tx_packets
);
947 INC_STAT(tunnel_tx_bytes
, l
);
951 // Tiny helper function to write data to
954 int tun_write(uint8_t * data
, int size
)
956 return write(tunfd
, data
, size
);
959 // process outgoing (to tunnel) IP
961 static void processipout(uint8_t * buf
, int len
)
968 char *data
= buf
; // Keep a copy of the originals.
971 uint8_t b
[MAXETHER
+ 20];
975 if (len
< MIN_IP_SIZE
)
977 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
983 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
988 // Skip the tun header
992 // Got an IP header now
993 if (*(uint8_t *)(buf
) >> 4 != 4)
995 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
999 ip
= *(uint32_t *)(buf
+ 16);
1000 if (!(s
= sessionbyip(ip
)))
1002 // Is this a packet for a session that doesn't exist?
1003 static int rate
= 0; // Number of ICMP packets we've sent this second.
1004 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1006 if (last
!= time_now
)
1012 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1014 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1015 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
1019 t
= session
[s
].tunnel
;
1022 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1023 if (config
->max_packets
> 0)
1025 if (sess_local
[s
].last_packet_out
== TIME
)
1027 int max
= config
->max_packets
;
1029 // All packets for throttled sessions are handled by the
1030 // master, so further limit by using the throttle rate.
1031 // A bit of a kludge, since throttle rate is in kbps,
1032 // but should still be generous given our average DSL
1033 // packet size is 200 bytes: a limit of 28kbps equates
1034 // to around 180 packets per second.
1035 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1036 max
= sp
->throttle_out
;
1038 if (++sess_local
[s
].packets_out
> max
)
1040 sess_local
[s
].packets_dropped
++;
1046 if (sess_local
[s
].packets_dropped
)
1048 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1049 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1050 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1051 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1055 sess_local
[s
].last_packet_out
= TIME
;
1056 sess_local
[s
].packets_out
= 1;
1057 sess_local
[s
].packets_dropped
= 0;
1061 // run access-list if any
1062 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1067 // Are we throttling this session?
1068 if (config
->cluster_iam_master
)
1069 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1071 master_throttle_packet(sp
->tbf_out
, data
, size
);
1074 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1076 // We are walled-gardening this
1077 master_garden_packet(s
, data
, size
);
1081 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1083 // Add on L2TP header
1085 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
1087 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1090 // Snooping this session, send it to intercept box
1091 if (sp
->snoop_ip
&& sp
->snoop_port
)
1092 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1094 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1095 sp
->cout_delta
+= len
;
1099 sess_local
[s
].cout
+= len
; // To send to master..
1100 sess_local
[s
].pout
++;
1103 // process outgoing (to tunnel) IPv6
1105 static void processipv6out(uint8_t * buf
, int len
)
1111 struct in6_addr ip6
;
1113 char *data
= buf
; // Keep a copy of the originals.
1116 uint8_t b
[MAXETHER
+ 20];
1118 CSTAT(processipv6out
);
1120 if (len
< MIN_IP_SIZE
)
1122 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1123 STAT(tunnel_tx_errors
);
1126 if (len
>= MAXETHER
)
1128 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1129 STAT(tunnel_tx_errors
);
1133 // Skip the tun header
1137 // Got an IP header now
1138 if (*(uint8_t *)(buf
) >> 4 != 6)
1140 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1144 ip6
= *(struct in6_addr
*)(buf
+24);
1145 s
= sessionbyipv6(ip6
);
1149 ip
= *(uint32_t *)(buf
+ 32);
1150 s
= sessionbyip(ip
);
1155 // Is this a packet for a session that doesn't exist?
1156 static int rate
= 0; // Number of ICMP packets we've sent this second.
1157 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1159 if (last
!= time_now
)
1165 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1167 // FIXME: Should send icmp6 host unreachable
1171 t
= session
[s
].tunnel
;
1174 // FIXME: add DoS prevention/filters?
1178 // Are we throttling this session?
1179 if (config
->cluster_iam_master
)
1180 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1182 master_throttle_packet(sp
->tbf_out
, data
, size
);
1185 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1187 // We are walled-gardening this
1188 master_garden_packet(s
, data
, size
);
1192 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1194 // Add on L2TP header
1196 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIPV6
);
1198 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1201 // Snooping this session, send it to intercept box
1202 if (sp
->snoop_ip
&& sp
->snoop_port
)
1203 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1205 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1206 sp
->cout_delta
+= len
;
1210 sess_local
[s
].cout
+= len
; // To send to master..
1211 sess_local
[s
].pout
++;
1215 // Helper routine for the TBF filters.
1216 // Used to send queued data in to the user!
1218 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1224 uint8_t b
[MAXETHER
+ 20];
1226 if (len
< 0 || len
> MAXETHER
)
1228 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1232 // Skip the tun header
1236 ip
= *(in_addr_t
*)(buf
+ 16);
1241 t
= session
[s
].tunnel
;
1244 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1246 // Add on L2TP header
1248 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
1250 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1253 // Snooping this session.
1254 if (sp
->snoop_ip
&& sp
->snoop_port
)
1255 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1257 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1258 sp
->cout_delta
+= len
;
1262 sess_local
[s
].cout
+= len
; // To send to master..
1263 sess_local
[s
].pout
++;
1266 // add an AVP (16 bit)
1267 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1269 uint16_t l
= (m
? 0x8008 : 0x0008);
1270 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1271 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1272 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1273 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1277 // add an AVP (32 bit)
1278 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1280 uint16_t l
= (m
? 0x800A : 0x000A);
1281 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1282 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1283 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1284 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1288 // add an AVP (string)
1289 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1291 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1292 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1293 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1294 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1295 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1296 c
->length
+= 6 + strlen(val
);
1300 static void controlb(controlt
* c
, uint16_t avp
, char *val
, unsigned int len
, uint8_t m
)
1302 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1303 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1304 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1305 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1306 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1307 c
->length
+= 6 + len
;
1310 // new control connection
1311 static controlt
*controlnew(uint16_t mtype
)
1315 c
= malloc(sizeof(controlt
));
1319 controlfree
= c
->next
;
1323 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1325 control16(c
, 0, mtype
, 1);
1329 // send zero block if nothing is waiting
1331 static void controlnull(tunnelidt t
)
1334 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1337 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1338 *(uint16_t *) (buf
+ 2) = htons(12); // length
1339 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1340 *(uint16_t *) (buf
+ 6) = htons(0); // session
1341 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1342 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1343 tunnelsend(buf
, 12, t
);
1346 // add a control message to a tunnel, and send if within window
1347 static void controladd(controlt
* c
, tunnelidt t
, sessionidt far
)
1349 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1350 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1351 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1352 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1353 tunnel
[t
].ns
++; // advance sequence
1354 // link in message in to queue
1355 if (tunnel
[t
].controlc
)
1356 tunnel
[t
].controle
->next
= c
;
1358 tunnel
[t
].controls
= c
;
1360 tunnel
[t
].controle
= c
;
1361 tunnel
[t
].controlc
++;
1363 // send now if space in window
1364 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1366 tunnel
[t
].try = 0; // first send
1367 tunnelsend(c
->buf
, c
->length
, t
);
1372 // Throttle or Unthrottle a session
1374 // Throttle the data from/to through a session to no more than
1375 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1378 // If either value is -1, the current value is retained for that
1381 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1383 if (!session
[s
].opened
)
1384 return; // No-one home.
1386 if (!*session
[s
].user
)
1387 return; // User not logged in
1391 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1392 if (session
[s
].tbf_in
)
1393 free_tbf(session
[s
].tbf_in
);
1396 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1398 session
[s
].tbf_in
= 0;
1400 session
[s
].throttle_in
= rate_in
;
1405 int bytes
= rate_out
* 1024 / 8;
1406 if (session
[s
].tbf_out
)
1407 free_tbf(session
[s
].tbf_out
);
1410 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1412 session
[s
].tbf_out
= 0;
1414 session
[s
].throttle_out
= rate_out
;
1418 // add/remove filters from session (-1 = no change)
1419 static void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1421 if (!session
[s
].opened
)
1422 return; // No-one home.
1424 if (!*session
[s
].user
)
1425 return; // User not logged in
1428 if (filter_in
> MAXFILTER
) filter_in
= -1;
1429 if (filter_out
> MAXFILTER
) filter_out
= -1;
1430 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1431 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1435 if (session
[s
].filter_in
)
1436 ip_filters
[session
[s
].filter_in
- 1].used
--;
1439 ip_filters
[filter_in
- 1].used
++;
1441 session
[s
].filter_in
= filter_in
;
1444 if (filter_out
>= 0)
1446 if (session
[s
].filter_out
)
1447 ip_filters
[session
[s
].filter_out
- 1].used
--;
1450 ip_filters
[filter_out
- 1].used
++;
1452 session
[s
].filter_out
= filter_out
;
1456 // start tidy shutdown of session
1457 void sessionshutdown(sessionidt s
, char *reason
, int result
, int error
)
1459 int walled_garden
= session
[s
].walled_garden
;
1462 CSTAT(sessionshutdown
);
1464 if (!session
[s
].opened
)
1466 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1467 return; // not a live session
1470 if (!session
[s
].die
)
1472 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1473 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1474 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1477 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1479 // RADIUS Stop message
1480 uint16_t r
= sess_local
[s
].radius
;
1486 // stop, if not already trying
1487 if (radius
[r
].state
!= RADIUSSTOP
)
1488 radiussend(r
, RADIUSSTOP
);
1491 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1493 // Save counters to dump to accounting file
1494 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1495 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1499 { // IP allocated, clear and unroute
1502 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1504 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1505 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1508 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1509 session
[s
].route
[r
].ip
= 0;
1512 if (session
[s
].ip_pool_index
== -1) // static ip
1514 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1520 // unroute IPv6, if setup
1521 if (session
[s
].flags
& SF_IPV6_ROUTED
)
1522 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1525 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1526 throttle_session(s
, 0, 0);
1530 controlt
*c
= controlnew(14); // sending CDN
1534 *(uint16_t *) buf
= htons(result
);
1535 *(uint16_t *) (buf
+2) = htons(error
);
1536 controlb(c
, 1, buf
, 4, 1);
1539 control16(c
, 1, result
, 1);
1541 control16(c
, 14, s
, 1); // assigned session (our end)
1542 controladd(c
, session
[s
].tunnel
, session
[s
].far
); // send the message
1545 if (!session
[s
].die
)
1546 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1548 // update filter refcounts
1549 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1550 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1552 cluster_send_session(s
);
1555 void sendipcp(tunnelidt t
, sessionidt s
)
1557 uint8_t buf
[MAXCONTROL
];
1558 uint16_t r
= sess_local
[s
].radius
;
1568 sessionshutdown(s
, "No free RADIUS sessions for IPCP", 3, 0);
1572 if (radius
[r
].state
!= RADIUSIPCP
)
1574 radius
[r
].state
= RADIUSIPCP
;
1578 radius
[r
].retry
= backoff(radius
[r
].try++);
1579 if (radius
[r
].try > 10)
1581 radiusclear(r
, s
); // Clear radius session.
1582 sessionshutdown(s
, "No reply to IPCP.", 3, 0);
1586 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1590 q
[1] = r
>> RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1591 *(uint16_t *) (q
+ 2) = htons(10);
1594 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1595 config
->bind_address
? config
->bind_address
:
1596 my_address
; // send my IP
1598 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1599 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1601 // If we have an IPv6 prefix length configured, assume we should
1602 // try to negotiate an IPv6 session as well. Unless we've had a
1603 // (N)ACK for IPV6CP.
1604 if (config
->ipv6_prefix
.s6_addr
[0] > 0 &&
1605 !(session
[s
].flags
& SF_IPV6CP_ACKED
) &&
1606 !(session
[s
].flags
& SF_IPV6_NACKED
))
1608 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPV6CP
);
1612 q
[1] = r
>> RADIUS_SHIFT
; // ID, don't care, we
1613 // only send one type
1615 *(uint16_t *) (q
+ 2) = htons(14);
1618 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
1619 *(uint32_t *) (q
+ 10) = 0;
1622 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
1626 static void sessionclear(sessionidt s
)
1628 memset(&session
[s
], 0, sizeof(session
[s
]));
1629 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
1630 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
1632 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1633 session
[s
].next
= sessionfree
;
1637 // kill a session now
1638 void sessionkill(sessionidt s
, char *reason
)
1643 if (!session
[s
].opened
) // not alive
1646 if (session
[s
].next
)
1648 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%d)\n", session
[s
].next
);
1652 session
[s
].die
= TIME
;
1653 sessionshutdown(s
, reason
, 3, 0); // close radius/routes, etc.
1654 if (sess_local
[s
].radius
)
1655 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
1657 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1659 cluster_send_session(s
);
1662 static void tunnelclear(tunnelidt t
)
1665 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1666 tunnel
[t
].state
= TUNNELFREE
;
1669 // kill a tunnel now
1670 static void tunnelkill(tunnelidt t
, char *reason
)
1677 tunnel
[t
].state
= TUNNELDIE
;
1679 // free control messages
1680 while ((c
= tunnel
[t
].controls
))
1682 controlt
* n
= c
->next
;
1683 tunnel
[t
].controls
= n
;
1684 tunnel
[t
].controlc
--;
1685 c
->next
= controlfree
;
1689 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1690 if (session
[s
].tunnel
== t
)
1691 sessionkill(s
, reason
);
1695 LOG(1, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1696 cli_tunnel_actions
[t
].action
= 0;
1697 cluster_send_tunnel(t
);
1700 // shut down a tunnel cleanly
1701 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
1705 CSTAT(tunnelshutdown
);
1707 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1709 // never set up, can immediately kill
1710 tunnelkill(t
, reason
);
1713 LOG(1, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1716 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1717 if (session
[s
].tunnel
== t
)
1718 sessionshutdown(s
, reason
, 3, 0);
1720 tunnel
[t
].state
= TUNNELDIE
;
1721 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
1722 cluster_send_tunnel(t
);
1723 // TBA - should we wait for sessions to stop?
1726 controlt
*c
= controlnew(4); // sending StopCCN
1731 *(uint16_t *) buf
= htons(result
);
1732 *(uint16_t *) (buf
+2) = htons(error
);
1735 int m
= strlen(msg
);
1736 if (m
+ 4 > sizeof(buf
))
1737 m
= sizeof(buf
) - 4;
1739 memcpy(buf
+4, msg
, m
);
1743 controlb(c
, 1, buf
, l
, 1);
1746 control16(c
, 1, result
, 1);
1748 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1749 controladd(c
, t
, 0); // send the message
1753 // read and process packet on tunnel (UDP)
1754 void processudp(uint8_t * buf
, int len
, struct sockaddr_in
*addr
)
1756 char *chapresponse
= NULL
;
1757 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1758 uint8_t *p
= buf
+ 2;
1765 LOG_HEX(5, "UDP Data", buf
, len
);
1766 STAT(tunnel_rx_packets
);
1767 INC_STAT(tunnel_rx_bytes
, len
);
1770 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
1771 STAT(tunnel_rx_errors
);
1774 if ((buf
[1] & 0x0F) != 2)
1776 LOG(1, 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1777 STAT(tunnel_rx_errors
);
1782 l
= ntohs(*(uint16_t *) p
);
1785 t
= ntohs(*(uint16_t *) p
);
1787 s
= ntohs(*(uint16_t *) p
);
1789 if (s
>= MAXSESSION
)
1791 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
1792 STAT(tunnel_rx_errors
);
1797 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
1798 STAT(tunnel_rx_errors
);
1803 ns
= ntohs(*(uint16_t *) p
);
1805 nr
= ntohs(*(uint16_t *) p
);
1810 uint16_t o
= ntohs(*(uint16_t *) p
);
1815 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
1816 STAT(tunnel_rx_errors
);
1822 uint16_t message
= 0xFFFF; // message type
1824 uint8_t mandatory
= 0;
1825 uint8_t authtype
= 0; // proxy auth type
1826 uint16_t asession
= 0; // assigned session
1827 uint32_t amagic
= 0; // magic number
1828 uint8_t aflags
= 0; // flags from last LCF
1829 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1830 char called
[MAXTEL
] = ""; // called number
1831 char calling
[MAXTEL
] = ""; // calling number
1833 if (!config
->cluster_iam_master
)
1835 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1839 // control messages must have bits 0x80|0x40|0x08
1840 // (type, length and sequence) set, and bits 0x02|0x01
1841 // (offset and priority) clear
1842 if ((*buf
& 0xCB) != 0xC8)
1844 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
1845 STAT(tunnel_rx_errors
);
1849 // check for duplicate tunnel open message
1855 // Is this a duplicate of the first packet? (SCCRQ)
1857 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1859 if (tunnel
[i
].state
!= TUNNELOPENING
||
1860 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
1861 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1864 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
1869 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1870 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1872 // if no tunnel specified, assign one
1875 if (!(t
= new_tunnel()))
1877 LOG(1, 0, 0, "No more tunnels\n");
1878 STAT(tunnel_overflow
);
1882 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
1883 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1884 tunnel
[t
].window
= 4; // default window
1885 STAT(tunnel_created
);
1886 LOG(1, 0, t
, " New tunnel from %s:%u ID %d\n",
1887 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
1890 // If the 'ns' just received is not the 'nr' we're
1891 // expecting, just send an ack and drop it.
1893 // if 'ns' is less, then we got a retransmitted packet.
1894 // if 'ns' is greater than missed a packet. Either way
1895 // we should ignore it.
1896 if (ns
!= tunnel
[t
].nr
)
1898 // is this the sequence we were expecting?
1899 STAT(tunnel_rx_errors
);
1900 LOG(1, 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n",
1901 t
, ns
, tunnel
[t
].nr
);
1903 if (l
) // Is this not a ZLB?
1908 // This is used to time out old tunnels
1909 tunnel
[t
].lastrec
= time_now
;
1911 // check sequence of this message
1913 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1914 // some to clear maybe?
1915 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1917 controlt
*c
= tunnel
[t
].controls
;
1918 tunnel
[t
].controls
= c
->next
;
1919 tunnel
[t
].controlc
--;
1920 c
->next
= controlfree
;
1923 tunnel
[t
].try = 0; // we have progress
1926 // receiver advance (do here so quoted correctly in any sends below)
1927 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1928 if (skip
< 0) skip
= 0;
1929 if (skip
< tunnel
[t
].controlc
)
1931 // some control packets can now be sent that were previous stuck out of window
1932 int tosend
= tunnel
[t
].window
- skip
;
1933 controlt
*c
= tunnel
[t
].controls
;
1941 tunnel
[t
].try = 0; // first send
1942 tunnelsend(c
->buf
, c
->length
, t
);
1947 if (!tunnel
[t
].controlc
)
1948 tunnel
[t
].retry
= 0; // caught up
1951 { // if not a null message
1957 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
1959 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
1965 LOG(1, s
, t
, "Invalid length in AVP\n");
1966 STAT(tunnel_rx_errors
);
1971 if (flags
& 0x3C) // reserved bits, should be clear
1973 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1975 result
= 2; // general error
1976 error
= 3; // reserved field non-zero
1981 if (*(uint16_t *) (b
))
1983 LOG(2, s
, t
, "Unknown AVP vendor %d\n", ntohs(*(uint16_t *) (b
)));
1985 result
= 2; // general error
1986 error
= 6; // generic vendor-specific error
1987 msg
= "unsupported vendor-specific";
1991 mtype
= ntohs(*(uint16_t *) (b
));
1999 // handle hidden AVPs
2000 if (!*config
->l2tpsecret
)
2002 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2004 result
= 2; // general error
2005 error
= 6; // generic vendor-specific error
2006 msg
= "secret not specified";
2009 if (!session
[s
].random_vector_length
)
2011 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2013 result
= 2; // general error
2014 error
= 6; // generic
2015 msg
= "no random vector";
2020 LOG(2, s
, t
, "Short hidden AVP.\n");
2022 result
= 2; // general error
2023 error
= 2; // length is wrong
2028 LOG(4, s
, t
, "Hidden AVP\n");
2031 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2033 orig_len
= ntohs(*(uint16_t *) b
);
2034 if (orig_len
> n
+ 2)
2036 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2040 result
= 2; // general error
2041 error
= 2; // length is wrong
2050 LOG(4, s
, t
, " AVP %d (%s) len %d\n", mtype
, avp_name(mtype
), n
);
2053 case 0: // message type
2054 message
= ntohs(*(uint16_t *) b
);
2055 mandatory
= flags
& 0x80;
2056 LOG(4, s
, t
, " Message type = %d (%s)\n", *b
, l2tp_message_type(message
));
2058 case 1: // result code
2060 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2061 const char* resdesc
= "(unknown)";
2064 resdesc
= stopccn_result_code(rescode
);
2066 else if (message
== 14)
2068 resdesc
= cdn_result_code(rescode
);
2071 LOG(4, s
, t
, " Result Code %d: %s\n", rescode
, resdesc
);
2074 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2075 LOG(4, s
, t
, " Error Code %d: %s\n", errcode
, error_code(errcode
));
2078 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2083 case 2: // protocol version
2085 version
= ntohs(*(uint16_t *) (b
));
2086 LOG(4, s
, t
, " Protocol version = %d\n", version
);
2087 if (version
&& version
!= 0x0100)
2088 { // allow 0.0 and 1.0
2089 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2091 result
= 5; // unspported protocol version
2092 error
= 0x0100; // supported version
2098 case 3: // framing capabilities
2099 // LOG(4, s, t, "Framing capabilities\n");
2101 case 4: // bearer capabilities
2102 // LOG(4, s, t, "Bearer capabilities\n");
2104 case 5: // tie breaker
2105 // We never open tunnels, so we don't care about tie breakers
2106 // LOG(4, s, t, "Tie breaker\n");
2108 case 6: // firmware revision
2109 // LOG(4, s, t, "Firmware revision\n");
2111 case 7: // host name
2112 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2113 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2114 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2115 // TBA - to send to RADIUS
2117 case 8: // vendor name
2118 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2119 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2120 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2122 case 9: // assigned tunnel
2123 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2124 LOG(4, s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
2126 case 10: // rx window
2127 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2128 if (!tunnel
[t
].window
)
2129 tunnel
[t
].window
= 1; // window of 0 is silly
2130 LOG(4, s
, t
, " rx window = %d\n", tunnel
[t
].window
);
2132 case 11: // Challenge
2134 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2135 build_chap_response(b
, 2, n
, &chapresponse
);
2138 case 13: // Response
2139 // Why did they send a response? We never challenge.
2140 LOG(2, s
, t
, " received unexpected challenge response\n");
2143 case 14: // assigned session
2144 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2145 LOG(4, s
, t
, " assigned session = %d\n", asession
);
2147 case 15: // call serial number
2148 LOG(4, s
, t
, " call serial number = %d\n", ntohl(*(uint32_t *)b
));
2150 case 18: // bearer type
2151 LOG(4, s
, t
, " bearer type = %d\n", ntohl(*(uint32_t *)b
));
2154 case 19: // framing type
2155 LOG(4, s
, t
, " framing type = %d\n", ntohl(*(uint32_t *)b
));
2158 case 21: // called number
2159 memset(called
, 0, sizeof(called
));
2160 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2161 LOG(4, s
, t
, " Called <%s>\n", called
);
2163 case 22: // calling number
2164 memset(calling
, 0, sizeof(calling
));
2165 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2166 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2170 case 24: // tx connect speed
2173 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2177 // AS5300s send connect speed as a string
2179 memset(tmp
, 0, sizeof(tmp
));
2180 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2181 session
[s
].tx_connect_speed
= atol(tmp
);
2183 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2185 case 38: // rx connect speed
2188 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2192 // AS5300s send connect speed as a string
2194 memset(tmp
, 0, sizeof(tmp
));
2195 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2196 session
[s
].rx_connect_speed
= atol(tmp
);
2198 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2200 case 25: // Physical Channel ID
2202 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2203 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2206 case 29: // Proxy Authentication Type
2208 uint16_t atype
= ntohs(*(uint16_t *)b
);
2209 LOG(4, s
, t
, " Proxy Auth Type %d (%s)\n", atype
, auth_type(atype
));
2211 authtype
= AUTHCHAP
;
2212 else if (atype
== 3)
2217 case 30: // Proxy Authentication Name
2220 memset(authname
, 0, sizeof(authname
));
2221 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2222 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2226 case 31: // Proxy Authentication Challenge
2228 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2229 if (sess_local
[s
].radius
)
2230 memcpy(radius
[sess_local
[s
].radius
].auth
, b
, 16);
2233 case 32: // Proxy Authentication ID
2235 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2236 LOG(4, s
, t
, " Proxy Auth ID (%d)\n", authid
);
2237 if (sess_local
[s
].radius
)
2238 radius
[sess_local
[s
].radius
].id
= authid
;
2241 case 33: // Proxy Authentication Response
2242 LOG(4, s
, t
, " Proxy Auth Response\n");
2244 case 27: // last sent lcp
2245 { // find magic number
2246 uint8_t *p
= b
, *e
= p
+ n
;
2247 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2249 if (*p
== 5 && p
[1] == 6) // Magic-Number
2250 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2251 else if (*p
== 3 && p
[1] == 4 && *(uint16_t *) (p
+ 2) == htons(PPPPAP
)) // Authentication-Protocol (PAP)
2253 else if (*p
== 3 && p
[1] == 5 && *(uint16_t *) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol (CHAP)
2254 authtype
= AUTHCHAP
;
2255 else if (*p
== 7) // Protocol-Field-Compression
2256 aflags
|= SESSIONPFC
;
2257 else if (*p
== 8) // Address-and-Control-Field-Compression
2258 aflags
|= SESSIONACFC
;
2263 case 28: // last recv lcp confreq
2265 case 26: // Initial Received LCP CONFREQ
2267 case 39: // seq required - we control it as an LNS anyway...
2269 case 36: // Random Vector
2270 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2271 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2272 memcpy(session
[s
].random_vector
, b
, n
);
2273 session
[s
].random_vector_length
= n
;
2277 static char e
[] = "unknown AVP 0xXXXX";
2278 LOG(2, s
, t
, " Unknown AVP type %d\n", mtype
);
2280 result
= 2; // general error
2281 error
= 8; // unknown mandatory AVP
2282 sprintf((msg
= e
) + 14, "%04x", mtype
);
2289 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2293 case 1: // SCCRQ - Start Control Connection Request
2295 controlt
*c
= controlnew(2); // sending SCCRP
2296 control16(c
, 2, version
, 1); // protocol version
2297 control32(c
, 3, 3, 1); // framing
2298 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
2299 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2300 control16(c
, 9, t
, 1); // assigned tunnel
2301 controladd(c
, t
, 0); // send the resply
2303 tunnel
[t
].state
= TUNNELOPENING
;
2306 tunnel
[t
].state
= TUNNELOPEN
;
2309 tunnel
[t
].state
= TUNNELOPEN
;
2310 controlnull(t
); // ack
2313 controlnull(t
); // ack
2314 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2317 controlnull(t
); // simply ACK
2334 sessionfree
= session
[s
].next
;
2335 memset(&session
[s
], 0, sizeof(session
[s
]));
2337 if (s
> config
->cluster_highest_sessionid
)
2338 config
->cluster_highest_sessionid
= s
;
2340 // make a RADIUS session
2341 if ((r
= radiusnew(s
)))
2343 controlt
*c
= controlnew(11); // sending ICRP
2344 session
[s
].opened
= time_now
;
2345 session
[s
].tunnel
= t
;
2346 session
[s
].far
= asession
;
2347 session
[s
].last_packet
= time_now
;
2348 LOG(3, s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
2349 control16(c
, 14, s
, 1); // assigned session
2350 controladd(c
, t
, asession
); // send the reply
2352 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
2353 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2354 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2355 STAT(session_created
);
2360 LOG(1, s
, t
, "No free RADIUS sessions for ICRQ\n");
2365 STAT(session_overflow
);
2366 LOG(1, 0, t
, "No free sessions\n");
2370 controlt
*c
= controlnew(14); // CDN
2371 control16(c
, 1, 4, 1); // temporary lack of resources
2372 controladd(c
, session
[s
].tunnel
, asession
); // send the message
2379 if (amagic
== 0) amagic
= time_now
;
2380 session
[s
].magic
= amagic
; // set magic number
2381 session
[s
].l2tp_flags
= aflags
; // set flags received
2382 LOG(3, s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
2383 controlnull(t
); // ack
2384 // proxy authentication type is not supported
2385 if (!(config
->radius_authtypes
& authtype
))
2386 authtype
= config
->radius_authprefer
;
2389 sendlcp(t
, s
, authtype
);
2392 controlnull(t
); // ack
2393 sessionshutdown(s
, "Closed (Received CDN).", 0, 0);
2396 LOG(1, s
, t
, "Missing message type\n");
2399 STAT(tunnel_rx_errors
);
2401 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2403 LOG(1, s
, t
, "Unknown message type %d\n", message
);
2406 if (chapresponse
) free(chapresponse
);
2407 cluster_send_tunnel(t
);
2411 LOG(4, s
, t
, " Got a ZLB ack\n");
2418 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
2419 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
2420 { // HDLC address header, discard
2426 LOG(1, s
, t
, "Short ppp length %d\n", l
);
2427 STAT(tunnel_rx_errors
);
2437 prot
= ntohs(*(uint16_t *) p
);
2442 if (s
&& !session
[s
].opened
) // Is something wrong??
2444 if (!config
->cluster_iam_master
)
2446 // Pass it off to the master to deal with..
2447 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2452 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
2453 STAT(tunnel_rx_errors
);
2459 session
[s
].last_packet
= time_now
;
2460 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2461 processpap(t
, s
, p
, l
);
2463 else if (prot
== PPPCHAP
)
2465 session
[s
].last_packet
= time_now
;
2466 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2467 processchap(t
, s
, p
, l
);
2469 else if (prot
== PPPLCP
)
2471 session
[s
].last_packet
= time_now
;
2472 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2473 processlcp(t
, s
, p
, l
);
2475 else if (prot
== PPPIPCP
)
2477 session
[s
].last_packet
= time_now
;
2478 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2479 processipcp(t
, s
, p
, l
);
2481 else if (prot
== PPPIPV6CP
)
2483 if (config
->ipv6_prefix
.s6_addr
[0] > 0)
2485 session
[s
].last_packet
= time_now
;
2486 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2487 processipv6cp(t
, s
, p
, l
);
2491 LOG(1, s
, t
, "IPv6 not configured; ignoring IPv6CP\n");
2494 else if (prot
== PPPCCP
)
2496 session
[s
].last_packet
= time_now
;
2497 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2498 processccp(t
, s
, p
, l
);
2500 else if (prot
== PPPIP
)
2504 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
2505 return; // closing session, PPP not processed
2508 session
[s
].last_packet
= time_now
;
2509 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2511 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2515 processipin(t
, s
, p
, l
);
2517 else if (prot
== PPPIPV6
)
2519 if (!config
->ipv6_prefix
.s6_addr
[0] > 0)
2521 LOG(1, s
, t
, "IPv6 not configured; yet received IPv6 packet. Ignoring.\n");
2526 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
2527 return; // closing session, PPP not processed
2530 session
[s
].last_packet
= time_now
;
2531 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2533 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2537 processipv6in(t
, s
, p
, l
);
2541 STAT(tunnel_rx_errors
);
2542 LOG(1, s
, t
, "Unknown PPP protocol %04X\n", prot
);
2547 // read and process packet on tun
2548 static void processtun(uint8_t * buf
, int len
)
2550 LOG_HEX(5, "Receive TUN Data", buf
, len
);
2551 STAT(tun_rx_packets
);
2552 INC_STAT(tun_rx_bytes
, len
);
2560 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
2561 STAT(tun_rx_errors
);
2565 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
2566 processipout(buf
, len
);
2567 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
2568 && config
->ipv6_prefix
.s6_addr
[0] > 0)
2569 processipv6out(buf
, len
);
2574 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
2575 // that we look at the whole of the tunnel, radius and session tables
2577 static void regular_cleanups(double period
)
2579 // Next tunnel, radius and session to check for actions on.
2580 static tunnelidt t
= 0;
2582 static sessionidt s
= 0;
2595 // divide up tables into slices based on the last run
2596 t_slice
= config
->cluster_highest_tunnelid
* period
;
2597 r_slice
= (MAXRADIUS
- 1) * period
;
2598 s_slice
= config
->cluster_highest_sessionid
* period
;
2602 else if (t_slice
> config
->cluster_highest_tunnelid
)
2603 t_slice
= config
->cluster_highest_tunnelid
;
2607 else if (r_slice
> (MAXRADIUS
- 1))
2608 r_slice
= MAXRADIUS
- 1;
2612 else if (s_slice
> config
->cluster_highest_sessionid
)
2613 s_slice
= config
->cluster_highest_sessionid
;
2615 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
2617 for (i
= 0; i
< t_slice
; i
++)
2620 if (t
> config
->cluster_highest_tunnelid
)
2623 // check for expired tunnels
2624 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2626 STAT(tunnel_timeout
);
2627 tunnelkill(t
, "Expired");
2631 // check for message resend
2632 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2634 // resend pending messages as timeout on reply
2635 if (tunnel
[t
].retry
<= TIME
)
2637 controlt
*c
= tunnel
[t
].controls
;
2638 uint8_t w
= tunnel
[t
].window
;
2639 tunnel
[t
].try++; // another try
2640 if (tunnel
[t
].try > 5)
2641 tunnelkill(t
, "Timeout on control message"); // game over
2645 tunnelsend(c
->buf
, c
->length
, t
);
2653 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2655 controlt
*c
= controlnew(6); // sending HELLO
2656 controladd(c
, t
, 0); // send the message
2657 LOG(3, 0, t
, "Sending HELLO message\n");
2661 // Check for tunnel changes requested from the CLI
2662 if ((a
= cli_tunnel_actions
[t
].action
))
2664 cli_tunnel_actions
[t
].action
= 0;
2665 if (a
& CLI_TUN_KILL
)
2667 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
2668 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
2674 for (i
= 0; i
< r_slice
; i
++)
2680 if (!radius
[r
].state
)
2683 if (radius
[r
].retry
<= TIME
)
2690 for (i
= 0; i
< s_slice
; i
++)
2693 if (s
> config
->cluster_highest_sessionid
)
2696 if (!session
[s
].opened
) // Session isn't in use
2699 // check for expired sessions
2702 if (session
[s
].die
<= TIME
)
2704 sessionkill(s
, "Expired");
2710 if (session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2712 // IPCP has not completed yet. Resend
2713 LOG(3, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2714 sendipcp(session
[s
].tunnel
, s
);
2718 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2719 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2721 sessionshutdown(s
, "No response to LCP ECHO requests.", 3, 0);
2722 STAT(session_timeout
);
2727 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
2728 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2730 uint8_t b
[MAXCONTROL
] = {0};
2732 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2736 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
2737 *(uint16_t *)(q
+ 2) = htons(8); // Length
2738 *(uint32_t *)(q
+ 4) = 0; // Magic Number (not supported)
2740 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2741 (int)(time_now
- session
[s
].last_packet
));
2742 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2746 // Check for actions requested from the CLI
2747 if ((a
= cli_session_actions
[s
].action
))
2751 cli_session_actions
[s
].action
= 0;
2752 if (a
& CLI_SESS_KILL
)
2754 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2755 sessionshutdown(s
, "Requested by administrator.", 3, 0);
2756 a
= 0; // dead, no need to check for other actions
2760 if (a
& CLI_SESS_NOSNOOP
)
2762 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2763 session
[s
].snoop_ip
= 0;
2764 session
[s
].snoop_port
= 0;
2768 else if (a
& CLI_SESS_SNOOP
)
2770 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2771 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
2772 cli_session_actions
[s
].snoop_port
);
2774 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2775 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2780 if (a
& CLI_SESS_NOTHROTTLE
)
2782 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2783 throttle_session(s
, 0, 0);
2787 else if (a
& CLI_SESS_THROTTLE
)
2789 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2790 cli_session_actions
[s
].throttle_in
,
2791 cli_session_actions
[s
].throttle_out
);
2793 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2798 if (a
& CLI_SESS_NOFILTER
)
2800 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
2801 filter_session(s
, 0, 0);
2805 else if (a
& CLI_SESS_FILTER
)
2807 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
2808 cli_session_actions
[s
].filter_in
,
2809 cli_session_actions
[s
].filter_out
);
2811 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
2817 cluster_send_session(s
);
2820 // RADIUS interim accounting
2821 if (config
->radius_accounting
&& config
->radius_interim
> 0
2822 && session
[s
].ip
&& !session
[s
].walled_garden
2823 && !sess_local
[s
].radius
// RADIUS already in progress
2824 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
)
2826 if (!(r
= radiusnew(s
)))
2828 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
2829 STAT(radius_overflow
);
2833 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
2834 session
[s
].user
, session
[s
].unique_id
);
2836 radiussend(r
, RADIUSINTERIM
);
2837 sess_local
[s
].last_interim
= time_now
;
2842 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
2843 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
2847 // Are we in the middle of a tunnel update, or radius
2850 static int still_busy(void)
2853 static time_t stopped_bgp
= 0;
2854 static clockt last_talked
= 0;
2855 static clockt start_busy_wait
= 0;
2857 if (!config
->cluster_iam_master
)
2864 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
2866 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2867 if (bgp_peers
[i
].state
== Established
)
2868 bgp_stop(&bgp_peers
[i
]);
2870 stopped_bgp
= time_now
;
2872 // we don't want to become master
2873 cluster_send_ping(0);
2878 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
2886 if (start_busy_wait
== 0)
2887 start_busy_wait
= TIME
;
2889 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2891 if (!tunnel
[i
].controlc
)
2894 if (last_talked
!= TIME
)
2896 LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i
);
2902 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2903 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2905 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2909 for (i
= 1; i
< MAXRADIUS
; i
++)
2911 if (radius
[i
].state
== RADIUSNULL
)
2913 if (radius
[i
].state
== RADIUSWAIT
)
2916 if (last_talked
!= TIME
)
2918 LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2927 static fd_set readset
;
2928 static int readset_n
= 0;
2930 // main loop - gets packets on tun or udp and processes them
2931 static void mainloop(void)
2936 clockt next_cluster_ping
= 0; // send initial ping immediately
2938 LOG(4, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2939 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2942 FD_SET(udpfd
, &readset
);
2943 FD_SET(tunfd
, &readset
);
2944 FD_SET(controlfd
, &readset
);
2945 FD_SET(clifd
, &readset
);
2946 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2948 if (tunfd
> readset_n
) readset_n
= tunfd
;
2949 if (controlfd
> readset_n
) readset_n
= controlfd
;
2950 if (clifd
> readset_n
) readset_n
= clifd
;
2951 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2953 while (!main_quit
|| still_busy())
2959 int bgp_set
[BGP_NUM_PEERS
];
2963 if (config
->reload_config
)
2965 // Update the config state based on config settings
2969 memcpy(&r
, &readset
, sizeof(fd_set
));
2971 to
.tv_usec
= 100000; // 1/10th of a second.
2975 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2977 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2980 FD_SET(bgp_peers
[i
].sock
, &r
);
2981 if (bgp_peers
[i
].sock
> n
)
2982 n
= bgp_peers
[i
].sock
;
2987 FD_SET(bgp_peers
[i
].sock
, &w
);
2988 if (bgp_peers
[i
].sock
> n
)
2989 n
= bgp_peers
[i
].sock
;
2993 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2995 n
= select(n
+ 1, &r
, 0, 0, &to
);
2998 STAT(select_called
);
3003 if (errno
== EINTR
||
3004 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3007 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3013 struct sockaddr_in addr
;
3017 int cluster_pkts
= 0;
3020 if (FD_ISSET(controlfd
, &r
))
3022 alen
= sizeof(addr
);
3023 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
, alen
);
3028 if (config
->cluster_iam_master
)
3030 for (i
= 0; i
< config
->num_radfds
; i
++)
3032 if (FD_ISSET(radfds
[i
], &r
))
3034 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
3041 if (FD_ISSET(clifd
, &r
))
3045 alen
= sizeof(addr
);
3046 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3052 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3058 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3060 int isr
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0;
3061 int isw
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0;
3062 bgp_process(&bgp_peers
[i
], isr
, isw
);
3068 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3071 if (FD_ISSET(udpfd
, &r
))
3073 alen
= sizeof(addr
);
3074 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3076 processudp(buf
, s
, &addr
);
3087 if (FD_ISSET(tunfd
, &r
))
3089 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3102 if (FD_ISSET(cluster_sockfd
, &r
))
3104 alen
= sizeof(addr
);
3105 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3107 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3112 FD_CLR(cluster_sockfd
, &r
);
3118 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3119 STAT(multi_read_used
);
3121 if (c
>= config
->multi_read_count
)
3123 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3124 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3126 STAT(multi_read_exceeded
);
3131 // Runs on every machine (master and slaves).
3132 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
3134 // Check to see which of the cluster is still alive..
3136 cluster_send_ping(basetime
); // Only does anything if we're a slave
3137 cluster_check_master(); // ditto.
3139 cluster_heartbeat(); // Only does anything if we're a master.
3140 cluster_check_slaves(); // ditto.
3142 master_update_counts(); // If we're a slave, send our byte counters to our master.
3144 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
3145 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
3147 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
3150 if (!config
->cluster_iam_master
)
3153 // Run token bucket filtering queue..
3154 // Only run it every 1/10th of a second.
3156 static clockt last_run
= 0;
3157 if (last_run
!= TIME
)
3164 // Handle timeouts, retries etc.
3166 static double last_clean
= 0;
3170 TIME
= now(&this_clean
);
3171 diff
= this_clean
- last_clean
;
3173 // Run during idle time (after we've handled
3174 // all incoming packets) or every 1/10th sec
3175 if (!more
|| diff
> 0.1)
3177 regular_cleanups(diff
);
3178 last_clean
= this_clean
;
3182 if (*config
->accounting_dir
)
3184 static clockt next_acct
= 0;
3185 static clockt next_shut_acct
= 0;
3187 if (next_acct
<= TIME
)
3189 // Dump accounting data
3190 next_acct
= TIME
+ ACCT_TIME
;
3191 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3194 else if (next_shut_acct
<= TIME
)
3196 // Dump accounting data for shutdown sessions
3197 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3204 // Are we the master and shutting down??
3205 if (config
->cluster_iam_master
)
3206 cluster_heartbeat(); // Flush any queued changes..
3208 // Ok. Notify everyone we're shutting down. If we're
3209 // the master, this will force an election.
3210 cluster_send_ping(0);
3213 // Important!!! We MUST not process any packets past this point!
3214 LOG(1, 0, 0, "Clean shutdown complete\n");
3217 static void stripdomain(char *host
)
3221 if ((p
= strchr(host
, '.')))
3227 FILE *resolv
= fopen("/etc/resolv.conf", "r");
3233 while (fgets(buf
, sizeof(buf
), resolv
))
3235 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
3238 if (!isspace(buf
[6]))
3242 while (isspace(*b
)) b
++;
3247 while (*b
&& !isspace(*b
)) b
++;
3249 if (buf
[0] == 'd') // domain is canonical
3255 // first search line
3258 // hold, may be subsequent domain line
3259 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
3270 int hl
= strlen(host
);
3271 int dl
= strlen(domain
);
3272 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
3273 host
[hl
-dl
- 1] = 0;
3277 *p
= 0; // everything after first dot
3282 // Init data structures
3283 static void initdata(int optdebug
, char *optconfig
)
3287 if (!(config
= shared_malloc(sizeof(configt
))))
3289 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
3293 memset(config
, 0, sizeof(configt
));
3294 time(&config
->start_time
);
3295 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
3296 config
->debug
= optdebug
;
3297 config
->num_tbfs
= MAXTBFS
;
3298 config
->rl_rate
= 28; // 28kbps
3299 config
->cluster_master_min_adv
= 1;
3300 strcpy(config
->random_device
, RANDOMDEVICE
);
3302 log_stream
= stderr
;
3305 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
3307 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
3310 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
3313 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
3315 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
3318 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
3320 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
3323 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
3325 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
3329 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
3331 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
3335 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
3337 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
3341 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
3343 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
3347 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
3349 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
3352 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
3354 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
3356 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
3359 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
3361 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
3363 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
3366 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
3368 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
3369 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
3370 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
3371 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
3373 // Put all the sessions on the free list marked as undefined.
3374 for (i
= 1; i
< MAXSESSION
; i
++)
3376 session
[i
].next
= i
+ 1;
3377 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
3379 session
[MAXSESSION
- 1].next
= 0;
3382 // Mark all the tunnels as undefined (waiting to be filled in by a download).
3383 for (i
= 1; i
< MAXTUNNEL
; i
++)
3384 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
3388 // Grab my hostname unless it's been specified
3389 gethostname(hostname
, sizeof(hostname
));
3390 stripdomain(hostname
);
3393 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
3396 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
3398 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
3404 static int assign_ip_address(sessionidt s
)
3408 time_t best_time
= time_now
;
3409 char *u
= session
[s
].user
;
3413 CSTAT(assign_ip_address
);
3415 for (i
= 1; i
< ip_pool_size
; i
++)
3417 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
3420 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
3427 if (ip_address_pool
[i
].last
< best_time
)
3430 if (!(best_time
= ip_address_pool
[i
].last
))
3431 break; // never used, grab this one
3437 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
3441 session
[s
].ip
= ip_address_pool
[best
].address
;
3442 session
[s
].ip_pool_index
= best
;
3443 ip_address_pool
[best
].assigned
= 1;
3444 ip_address_pool
[best
].last
= time_now
;
3445 ip_address_pool
[best
].session
= s
;
3446 if (session
[s
].walled_garden
)
3447 /* Don't track addresses of users in walled garden (note: this
3448 means that their address isn't "sticky" even if they get
3450 ip_address_pool
[best
].user
[0] = 0;
3452 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
3455 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
3456 reuse
? "Reusing" : "Allocating", best
);
3461 static void free_ip_address(sessionidt s
)
3463 int i
= session
[s
].ip_pool_index
;
3466 CSTAT(free_ip_address
);
3469 return; // what the?
3471 if (i
< 0) // Is this actually part of the ip pool?
3475 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
3477 ip_address_pool
[i
].assigned
= 0;
3478 ip_address_pool
[i
].session
= 0;
3479 ip_address_pool
[i
].last
= time_now
;
3483 // Fsck the address pool against the session table.
3484 // Normally only called when we become a master.
3486 // This isn't perfect: We aren't keep tracking of which
3487 // users used to have an IP address.
3489 void rebuild_address_pool(void)
3494 // Zero the IP pool allocation, and build
3495 // a map from IP address to pool index.
3496 for (i
= 1; i
< MAXIPPOOL
; ++i
)
3498 ip_address_pool
[i
].assigned
= 0;
3499 ip_address_pool
[i
].session
= 0;
3500 if (!ip_address_pool
[i
].address
)
3503 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
3506 for (i
= 0; i
< MAXSESSION
; ++i
)
3509 if (!(session
[i
].opened
&& session
[i
].ip
))
3512 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
3514 if (session
[i
].ip_pool_index
< 0)
3516 // Not allocated out of the pool.
3517 if (ipid
< 1) // Not found in the pool either? good.
3520 LOG(0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
3521 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
3523 // Fall through and process it as part of the pool.
3527 if (ipid
> MAXIPPOOL
|| ipid
< 0)
3529 LOG(0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
3531 session
[i
].ip_pool_index
= ipid
;
3535 ip_address_pool
[ipid
].assigned
= 1;
3536 ip_address_pool
[ipid
].session
= i
;
3537 ip_address_pool
[ipid
].last
= time_now
;
3538 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
3539 session
[i
].ip_pool_index
= ipid
;
3540 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
3545 // Fix the address pool to match a changed session.
3546 // (usually when the master sends us an update).
3547 static void fix_address_pool(int sid
)
3551 ipid
= session
[sid
].ip_pool_index
;
3553 if (ipid
> ip_pool_size
)
3554 return; // Ignore it. rebuild_address_pool will fix it up.
3556 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
3557 return; // Just ignore it. rebuild_address_pool will take care of it.
3559 ip_address_pool
[ipid
].assigned
= 1;
3560 ip_address_pool
[ipid
].session
= sid
;
3561 ip_address_pool
[ipid
].last
= time_now
;
3562 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
3566 // Add a block of addresses to the IP pool to hand out.
3568 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
3572 mask
= 0xffffffff; // Host route only.
3576 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
3579 for (i
= addr
;(i
& mask
) == addr
; ++i
)
3581 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
3582 continue; // Skip 0 and broadcast addresses.
3584 ip_address_pool
[ip_pool_size
].address
= i
;
3585 ip_address_pool
[ip_pool_size
].assigned
= 0;
3587 if (ip_pool_size
>= MAXIPPOOL
)
3589 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
3595 // Initialize the IP address pool
3596 static void initippool()
3601 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
3603 if (!(f
= fopen(IPPOOLFILE
, "r")))
3605 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
3609 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
3612 buf
[4095] = 0; // Force it to be zero terminated/
3614 if (*buf
== '#' || *buf
== '\n')
3615 continue; // Skip comments / blank lines
3616 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
3617 if ((p
= (char *)strchr(buf
, ':')))
3621 src
= inet_addr(buf
);
3622 if (src
== INADDR_NONE
)
3624 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
3627 // This entry is for a specific IP only
3628 if (src
!= config
->bind_address
)
3633 if ((p
= (char *)strchr(pool
, '/')))
3637 in_addr_t start
= 0, mask
= 0;
3639 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
3641 if (!*p
|| !(numbits
= atoi(p
)))
3643 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
3646 start
= ntohl(inet_addr(pool
));
3647 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
3649 // Add a static route for this pool
3650 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
3651 fmtaddr(htonl(start
), 0), 32 + mask
);
3653 routeset(0, start
, mask
, 0, 1);
3655 add_to_ip_pool(start
, mask
);
3659 // It's a single ip address
3660 add_to_ip_pool(inet_addr(pool
), 0);
3664 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
3667 void snoop_send_packet(char *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
3669 struct sockaddr_in snoop_addr
= {0};
3670 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
3673 snoop_addr
.sin_family
= AF_INET
;
3674 snoop_addr
.sin_addr
.s_addr
= destination
;
3675 snoop_addr
.sin_port
= ntohs(port
);
3677 LOG(5, 0, 0, "Snooping %d byte packet to %s:%d\n", size
,
3678 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
3679 htons(snoop_addr
.sin_port
));
3681 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
3682 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
3684 STAT(packets_snooped
);
3687 static int dump_session(FILE **f
, sessiont
*s
)
3689 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
3694 char filename
[1024];
3696 time_t now
= time(NULL
);
3698 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
3699 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
3701 if (!(*f
= fopen(filename
, "w")))
3703 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
3707 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
3708 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
3712 "# format: username ip qos uptxoctets downrxoctets\n",
3718 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
3719 fprintf(*f
, "%s %s %d %u %u\n",
3720 s
->user
, // username
3721 fmtaddr(htonl(s
->ip
), 0), // ip
3722 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
3723 (uint32_t) s
->cin_delta
, // uptxoctets
3724 (uint32_t) s
->cout_delta
); // downrxoctets
3726 s
->cin_delta
= s
->cout_delta
= 0;
3731 static void dump_acct_info(int all
)
3737 CSTAT(dump_acct_info
);
3741 for (i
= 0; i
< shut_acct_n
; i
++)
3742 dump_session(&f
, &shut_acct
[i
]);
3748 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3749 dump_session(&f
, &session
[i
]);
3756 int main(int argc
, char *argv
[])
3760 char *optconfig
= CONFIGFILE
;
3762 time(&basetime
); // start clock
3765 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
3770 if (fork()) exit(0);
3772 freopen("/dev/null", "r", stdin
);
3773 freopen("/dev/null", "w", stdout
);
3774 freopen("/dev/null", "w", stderr
);
3783 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
3786 printf("Args are:\n"
3787 "\t-d\t\tDetach from terminal\n"
3788 "\t-c <file>\tConfig file\n"
3789 "\t-h <hostname>\tForce hostname\n"
3797 // Start the timer routine off
3799 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3800 signal(SIGALRM
, sigalrm_handler
);
3801 siginterrupt(SIGALRM
, 0);
3804 initdata(optdebug
, optconfig
);
3808 init_tbf(config
->num_tbfs
);
3810 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
3811 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005 Optus Internet Engineering\n");
3812 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3815 rlim
.rlim_cur
= RLIM_INFINITY
;
3816 rlim
.rlim_max
= RLIM_INFINITY
;
3817 // Remove the maximum core size
3818 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
3819 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
3821 // Make core dumps go to /tmp
3825 if (config
->scheduler_fifo
)
3828 struct sched_param params
= {0};
3829 params
.sched_priority
= 1;
3831 if (get_nprocs() < 2)
3833 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3834 config
->scheduler_fifo
= 0;
3838 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3840 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3844 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3845 config
->scheduler_fifo
= 0;
3850 /* Set up the cluster communications port. */
3851 if (cluster_init() < 0)
3855 signal(SIGPIPE
, SIG_IGN
);
3856 bgp_setup(config
->as_number
);
3857 bgp_add_route(config
->bind_address
, 0xffffffff);
3858 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3860 if (config
->neighbour
[i
].name
[0])
3861 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3862 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3863 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3868 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3874 signal(SIGHUP
, sighup_handler
);
3875 signal(SIGTERM
, sigterm_handler
);
3876 signal(SIGINT
, sigterm_handler
);
3877 signal(SIGQUIT
, sigquit_handler
);
3878 signal(SIGCHLD
, sigchild_handler
);
3880 // Prevent us from getting paged out
3881 if (config
->lock_pages
)
3883 if (!mlockall(MCL_CURRENT
))
3884 LOG(1, 0, 0, "Locking pages into memory\n");
3886 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3891 // Drop privileges here
3892 if (config
->target_uid
> 0 && geteuid() == 0)
3893 setuid(config
->target_uid
);
3897 /* remove plugins (so cleanup code gets run) */
3900 // Remove the PID file if we wrote it
3901 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3902 unlink(config
->pid_file
);
3904 /* kill CLI children */
3905 signal(SIGTERM
, SIG_IGN
);
3910 static void sighup_handler(int sig
)
3914 if (log_stream
!= stderr
)
3923 static void sigalrm_handler(int sig
)
3925 // Log current traffic stats
3927 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3928 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3929 (udp_rx
/ 1024.0 / 1024.0 * 8),
3930 (eth_tx
/ 1024.0 / 1024.0 * 8),
3931 (eth_rx
/ 1024.0 / 1024.0 * 8),
3932 (udp_tx
/ 1024.0 / 1024.0 * 8),
3933 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3934 udp_rx_pkt
, eth_rx_pkt
);
3936 udp_tx
= udp_rx
= 0;
3937 udp_rx_pkt
= eth_rx_pkt
= 0;
3938 eth_tx
= eth_rx
= 0;
3940 if (config
->dump_speed
)
3941 printf("%s\n", config
->bandwidth
);
3943 // Update the internal time counter
3945 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3950 struct param_timer p
= { time_now
};
3951 run_plugins(PLUGIN_TIMER
, &p
);
3956 static void sigterm_handler(int sig
)
3958 LOG(1, 0, 0, "Shutting down cleanly\n");
3962 static void sigquit_handler(int sig
)
3966 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3968 if (config
->cluster_iam_master
)
3970 for (i
= 1; i
< MAXSESSION
; i
++)
3972 if (session
[i
].opened
)
3973 sessionkill(i
, "L2TPNS Closing");
3975 for (i
= 1; i
< MAXTUNNEL
; i
++)
3977 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3978 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3985 static void sigchild_handler(int sig
)
3987 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3991 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
)
3994 *challenge_response
= NULL
;
3996 if (!*config
->l2tpsecret
)
3998 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4002 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4004 *challenge_response
= (char *)calloc(17, 1);
4007 MD5Update(&ctx
, &id
, 1);
4008 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4009 MD5Update(&ctx
, challenge
, challenge_length
);
4010 MD5Final(*challenge_response
, &ctx
);
4015 static int facility_value(char *name
)
4018 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4020 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4021 return facilitynames
[i
].c_val
;
4026 static void update_config()
4030 static int timeout
= 0;
4031 static int interval
= 0;
4038 if (log_stream
!= stderr
)
4044 if (*config
->log_filename
)
4046 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4048 char *p
= config
->log_filename
+ 7;
4051 openlog("l2tpns", LOG_PID
, facility_value(p
));
4055 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4057 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4059 fseek(log_stream
, 0, SEEK_END
);
4060 setbuf(log_stream
, NULL
);
4064 log_stream
= stderr
;
4065 setbuf(log_stream
, NULL
);
4071 log_stream
= stderr
;
4072 setbuf(log_stream
, NULL
);
4076 config
->numradiusservers
= 0;
4077 for (i
= 0; i
< MAXRADSERVER
; i
++)
4078 if (config
->radiusserver
[i
])
4080 config
->numradiusservers
++;
4081 // Set radius port: if not set, take the port from the
4082 // first radius server. For the first radius server,
4083 // take the #defined default value from l2tpns.h
4085 // test twice, In case someone works with
4086 // a secondary radius server without defining
4087 // a primary one, this will work even then.
4088 if (i
> 0 && !config
->radiusport
[i
])
4089 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4090 if (!config
->radiusport
[i
])
4091 config
->radiusport
[i
] = RADPORT
;
4094 if (!config
->numradiusservers
)
4095 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4097 config
->num_radfds
= 1 << RADIUS_SHIFT
;
4099 // parse radius_authtypes_s
4100 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4101 p
= config
->radius_authtypes_s
;
4104 char *s
= strpbrk(p
, " \t,");
4110 while (*s
== ' ' || *s
== '\t')
4117 if (!strncasecmp("chap", p
, strlen(p
)))
4119 else if (!strncasecmp("pap", p
, strlen(p
)))
4122 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4124 config
->radius_authtypes
|= type
;
4125 if (!config
->radius_authprefer
)
4126 config
->radius_authprefer
= type
;
4131 if (!config
->radius_authtypes
)
4133 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4134 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4137 // normalise radius_authtypes_s
4138 if (config
->radius_authprefer
== AUTHPAP
)
4140 strcpy(config
->radius_authtypes_s
, "pap");
4141 if (config
->radius_authtypes
& AUTHCHAP
)
4142 strcat(config
->radius_authtypes_s
, ", chap");
4146 strcpy(config
->radius_authtypes_s
, "chap");
4147 if (config
->radius_authtypes
& AUTHPAP
)
4148 strcat(config
->radius_authtypes_s
, ", pap");
4151 // re-initialise the random number source
4152 initrandom(config
->random_device
);
4155 for (i
= 0; i
< MAXPLUGINS
; i
++)
4157 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
4160 if (*config
->plugins
[i
])
4163 add_plugin(config
->plugins
[i
]);
4165 else if (*config
->old_plugins
[i
])
4168 remove_plugin(config
->old_plugins
[i
]);
4172 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
4173 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
4174 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
4175 if (!*config
->cluster_interface
)
4176 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
4178 if (!config
->cluster_hb_interval
)
4179 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
4181 if (!config
->cluster_hb_timeout
)
4182 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
4184 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
4186 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
4187 // late, ensure we're sufficiently larger than that
4188 int t
= 4 * config
->cluster_hb_interval
+ 11;
4190 if (config
->cluster_hb_timeout
< t
)
4192 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
4193 config
->cluster_hb_timeout
= t
;
4196 // Push timing changes to the slaves immediately if we're the master
4197 if (config
->cluster_iam_master
)
4198 cluster_heartbeat();
4200 interval
= config
->cluster_hb_interval
;
4201 timeout
= config
->cluster_hb_timeout
;
4205 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
4208 if ((f
= fopen(config
->pid_file
, "w")))
4210 fprintf(f
, "%d\n", getpid());
4212 config
->wrote_pid
= 1;
4216 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
4220 config
->reload_config
= 0;
4223 static void read_config_file()
4227 if (!config
->config_file
) return;
4228 if (!(f
= fopen(config
->config_file
, "r")))
4230 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
4234 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
4236 LOG(3, 0, 0, "Done reading config file\n");
4241 int sessionsetup(tunnelidt t
, sessionidt s
)
4243 // A session now exists, set it up
4249 CSTAT(sessionsetup
);
4251 LOG(3, s
, t
, "Doing session setup for session\n");
4255 assign_ip_address(s
);
4258 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
4259 sessionshutdown(s
, "No IP addresses available.", 2, 7);
4262 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
4263 fmtaddr(htonl(session
[s
].ip
), 0));
4267 // Make sure this is right
4268 session
[s
].tunnel
= t
;
4270 // zap old sessions with same IP and/or username
4271 // Don't kill gardened sessions - doing so leads to a DoS
4272 // from someone who doesn't need to know the password
4275 user
= session
[s
].user
;
4276 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4278 if (i
== s
) continue;
4279 if (!session
[s
].opened
) continue;
4280 if (ip
== session
[i
].ip
)
4282 sessionkill(i
, "Duplicate IP address");
4286 if (config
->allow_duplicate_users
) continue;
4287 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
4288 if (!strcasecmp(user
, session
[i
].user
))
4289 sessionkill(i
, "Duplicate session for users");
4296 // Add the route for this session.
4297 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
4299 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
4300 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
4303 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
4306 // Static IPs need to be routed if not already
4307 // convered by a Framed-Route. Anything else is part
4308 // of the IP address pool and is already routed, it
4309 // just needs to be added to the IP cache.
4310 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
4311 if (session
[s
].ip_pool_index
== -1) // static ip
4313 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
4316 cache_ipmap(session
[s
].ip
, s
);
4319 if (!session
[s
].unique_id
)
4321 // did this session just finish radius?
4322 LOG(3, s
, t
, "Sending initial IPCP to client\n");
4324 session
[s
].unique_id
= ++last_id
;
4327 // Run the plugin's against this new session.
4329 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
4330 run_plugins(PLUGIN_NEW_SESSION
, &data
);
4333 // Allocate TBFs if throttled
4334 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
4335 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
4337 session
[s
].last_packet
= time_now
;
4339 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
4340 fmtaddr(htonl(session
[s
].ip
), 0),
4341 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
4343 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
4345 return 1; // RADIUS OK and IP allocated, done...
4349 // This session just got dropped on us by the master or something.
4350 // Make sure our tables up up to date...
4352 int load_session(sessionidt s
, sessiont
*new)
4358 if (new->ip_pool_index
>= MAXIPPOOL
||
4359 new->tunnel
>= MAXTUNNEL
)
4361 LOG(0, s
, 0, "Strange session update received!\n");
4362 // FIXME! What to do here?
4367 // Ok. All sanity checks passed. Now we're committed to
4368 // loading the new session.
4371 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
4373 // See if routes/ip cache need updating
4374 if (new->ip
!= session
[s
].ip
)
4377 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
4378 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
4379 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
4387 // remove old routes...
4388 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
4390 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
4391 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
4394 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
4400 if (session
[s
].ip_pool_index
== -1) // static IP
4402 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
4404 else // It's part of the IP pool, remove it manually.
4405 uncache_ipmap(session
[s
].ip
);
4410 // add new routes...
4411 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
4413 if ((new->ip
& new->route
[i
].mask
) ==
4414 (new->route
[i
].ip
& new->route
[i
].mask
))
4417 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
4423 // If there's a new one, add it.
4424 if (new->ip_pool_index
== -1)
4426 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
4429 cache_ipmap(new->ip
, s
);
4434 if (new->flags
& SF_IPV6_ROUTED
&& !(session
[s
].flags
& SF_IPV6_ROUTED
))
4435 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
4438 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
4440 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %d\n", (int) new->filter_in
);
4444 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
4446 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %d\n", (int) new->filter_out
);
4447 new->filter_out
= 0;
4450 if (new->filter_in
!= session
[s
].filter_in
)
4452 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
4453 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
4456 if (new->filter_out
!= session
[s
].filter_out
)
4458 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
4459 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
4462 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
4463 // for walking the sessions to forward byte counts to the master.
4464 config
->cluster_highest_sessionid
= s
;
4466 // TEMP: old session struct used a uint32_t to define the throttle
4467 // speed for both up/down, new uses a uint16_t for each. Deal with
4468 // sessions from an old master for migration.
4469 if (new->throttle_out
== 0 && new->tbf_out
)
4470 new->throttle_out
= new->throttle_in
;
4472 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
4474 // Do fixups into address pool.
4475 if (new->ip_pool_index
!= -1)
4476 fix_address_pool(s
);
4481 static void initplugins()
4485 loaded_plugins
= ll_init();
4486 // Initialize the plugins to nothing
4487 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
4488 plugins
[i
] = ll_init();
4491 static void *open_plugin(char *plugin_name
, int load
)
4493 char path
[256] = "";
4495 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
4496 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
4497 return dlopen(path
, RTLD_NOW
);
4500 // plugin callback to get a config value
4501 static void *getconfig(char *key
, enum config_typet type
)
4505 for (i
= 0; config_values
[i
].key
; i
++)
4507 if (!strcmp(config_values
[i
].key
, key
))
4509 if (config_values
[i
].type
== type
)
4510 return ((void *) config
) + config_values
[i
].offset
;
4512 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
4513 key
, type
, config_values
[i
].type
);
4519 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
4523 static int add_plugin(char *plugin_name
)
4525 static struct pluginfuncs funcs
= {
4530 sessiontbysessionidt
,
4531 sessionidtbysessiont
,
4538 cluster_send_session
,
4541 void *p
= open_plugin(plugin_name
, 1);
4542 int (*initfunc
)(struct pluginfuncs
*);
4547 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
4551 if (ll_contains(loaded_plugins
, p
))
4554 return 0; // already loaded
4558 int *v
= dlsym(p
, "plugin_api_version");
4559 if (!v
|| *v
!= PLUGIN_API_VERSION
)
4561 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
4567 if ((initfunc
= dlsym(p
, "plugin_init")))
4569 if (!initfunc(&funcs
))
4571 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
4577 ll_push(loaded_plugins
, p
);
4579 for (i
= 0; i
< max_plugin_functions
; i
++)
4582 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4584 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
4585 ll_push(plugins
[i
], x
);
4589 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
4593 static void run_plugin_done(void *plugin
)
4595 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
4601 static int remove_plugin(char *plugin_name
)
4603 void *p
= open_plugin(plugin_name
, 0);
4609 if (ll_contains(loaded_plugins
, p
))
4612 for (i
= 0; i
< max_plugin_functions
; i
++)
4615 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4616 ll_delete(plugins
[i
], x
);
4619 ll_delete(loaded_plugins
, p
);
4625 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
4629 int run_plugins(int plugin_type
, void *data
)
4631 int (*func
)(void *data
);
4633 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
4634 return PLUGIN_RET_ERROR
;
4636 ll_reset(plugins
[plugin_type
]);
4637 while ((func
= ll_next(plugins
[plugin_type
])))
4641 if (r
!= PLUGIN_RET_OK
)
4642 return r
; // stop here
4645 return PLUGIN_RET_OK
;
4648 static void plugins_done()
4652 ll_reset(loaded_plugins
);
4653 while ((p
= ll_next(loaded_plugins
)))
4657 static void processcontrol(uint8_t * buf
, int len
, struct sockaddr_in
*addr
, int alen
)
4659 struct nsctl request
;
4660 struct nsctl response
;
4661 int type
= unpack_control(&request
, buf
, len
);
4665 if (log_stream
&& config
->debug
>= 4)
4669 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4670 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
4674 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4675 dump_control(&request
, log_stream
);
4681 case NSCTL_REQ_LOAD
:
4682 if (request
.argc
!= 1)
4684 response
.type
= NSCTL_RES_ERR
;
4686 response
.argv
[0] = "name of plugin required";
4688 else if ((r
= add_plugin(request
.argv
[0])) < 1)
4690 response
.type
= NSCTL_RES_ERR
;
4692 response
.argv
[0] = !r
4693 ? "plugin already loaded"
4694 : "error loading plugin";
4698 response
.type
= NSCTL_RES_OK
;
4704 case NSCTL_REQ_UNLOAD
:
4705 if (request
.argc
!= 1)
4707 response
.type
= NSCTL_RES_ERR
;
4709 response
.argv
[0] = "name of plugin required";
4711 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
4713 response
.type
= NSCTL_RES_ERR
;
4715 response
.argv
[0] = !r
4716 ? "plugin not loaded"
4717 : "plugin not found";
4721 response
.type
= NSCTL_RES_OK
;
4727 case NSCTL_REQ_HELP
:
4728 response
.type
= NSCTL_RES_OK
;
4731 ll_reset(loaded_plugins
);
4732 while ((p
= ll_next(loaded_plugins
)))
4734 char **help
= dlsym(p
, "plugin_control_help");
4735 while (response
.argc
< 0xff && help
&& *help
)
4736 response
.argv
[response
.argc
++] = *help
++;
4741 case NSCTL_REQ_CONTROL
:
4743 struct param_control param
= {
4744 config
->cluster_iam_master
,
4751 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4753 if (r
== PLUGIN_RET_ERROR
)
4755 response
.type
= NSCTL_RES_ERR
;
4757 response
.argv
[0] = param
.additional
4759 : "error returned by plugin";
4761 else if (r
== PLUGIN_RET_NOTMASTER
)
4763 static char msg
[] = "must be run on master: 000.000.000.000";
4765 response
.type
= NSCTL_RES_ERR
;
4767 if (config
->cluster_master_address
)
4769 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
4770 response
.argv
[0] = msg
;
4774 response
.argv
[0] = "must be run on master: none elected";
4777 else if (!(param
.response
& NSCTL_RESPONSE
))
4779 response
.type
= NSCTL_RES_ERR
;
4781 response
.argv
[0] = param
.response
4782 ? "unrecognised response value from plugin"
4783 : "unhandled action";
4787 response
.type
= param
.response
;
4789 if (param
.additional
)
4792 response
.argv
[0] = param
.additional
;
4800 response
.type
= NSCTL_RES_ERR
;
4802 response
.argv
[0] = "error unpacking control packet";
4805 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4808 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4812 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4815 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4816 if (log_stream
&& config
->debug
>= 4)
4818 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4819 dump_control(&response
, log_stream
);
4823 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4824 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
4829 static tunnelidt
new_tunnel()
4832 for (i
= 1; i
< MAXTUNNEL
; i
++)
4834 if (tunnel
[i
].state
== TUNNELFREE
)
4836 LOG(4, 0, i
, "Assigning tunnel ID %d\n", i
);
4837 if (i
> config
->cluster_highest_tunnelid
)
4838 config
->cluster_highest_tunnelid
= i
;
4842 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4847 // We're becoming the master. Do any required setup..
4849 // This is principally telling all the plugins that we're
4850 // now a master, and telling them about all the sessions
4851 // that are active too..
4853 void become_master(void)
4856 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4858 // running a bunch of iptables commands is slow and can cause
4859 // the master to drop tunnels on takeover--kludge around the
4860 // problem by forking for the moment (note: race)
4861 if (!fork_and_close())
4863 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4865 if (!session
[s
].opened
) // Not an in-use session.
4868 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4874 for (i
= 0; i
< config
->num_radfds
; i
++)
4876 FD_SET(radfds
[i
], &readset
);
4877 if (radfds
[i
] > readset_n
)
4878 readset_n
= radfds
[i
];
4882 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4888 if (CLI_HELP_REQUESTED
)
4889 return CLI_HELP_NO_ARGS
;
4892 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4894 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4897 if (!session
[s
].opened
)
4900 idle
= time_now
- session
[s
].last_packet
;
4901 idle
/= 5 ; // In multiples of 5 seconds.
4911 for (i
= 0; i
< 63; ++i
)
4913 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4915 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4916 cli_print(cli
, "%d total sessions open.", count
);
4920 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4926 if (CLI_HELP_REQUESTED
)
4927 return CLI_HELP_NO_ARGS
;
4930 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4932 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4935 if (!session
[s
].opened
)
4938 d
= time_now
- session
[s
].opened
;
4941 while (d
> 1 && open
< 32)
4951 for (i
= 0; i
< 30; ++i
)
4953 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4956 cli_print(cli
, "%d total sessions open.", count
);
4962 * This unencodes the AVP using the L2TP secret and the previously
4963 * stored random vector. It overwrites the hidden data with the
4964 * unhidden AVP subformat.
4966 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
4973 // Compute initial pad
4975 MD5Update(&ctx
, (uint8_t) (type
>> 8) & 0xff, 1);
4976 MD5Update(&ctx
, (uint8_t) type
& 0xff, 1);
4977 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4978 MD5Update(&ctx
, vector
, vec_len
);
4979 MD5Final(digest
, &ctx
);
4981 // pointer to last decoded 16 octets
4986 // calculate a new pad based on the last decoded block
4987 if (d
>= sizeof(digest
))
4990 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4991 MD5Update(&ctx
, last
, sizeof(digest
));
4992 MD5Final(digest
, &ctx
);
4998 *value
++ ^= digest
[d
++];
5003 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5007 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5008 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5009 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5010 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5011 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5017 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5021 case FILTER_FLAG_OP_ANY
:
5022 return (flags
& sflags
) || (~flags
& cflags
);
5024 case FILTER_FLAG_OP_ALL
:
5025 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5027 case FILTER_FLAG_OP_EST
:
5028 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5034 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5036 uint16_t frag_offset
;
5040 uint16_t src_port
= 0;
5041 uint16_t dst_port
= 0;
5043 ip_filter_rulet
*rule
;
5045 if (len
< 20) // up to end of destination address
5048 if ((*buf
>> 4) != 4) // IPv4
5051 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5053 src_ip
= *(in_addr_t
*) (buf
+ 12);
5054 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5056 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5058 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5059 if (len
< l
+ 4) // ports
5062 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
5063 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
5064 if (proto
== IPPROTO_TCP
)
5066 if (len
< l
+ 14) // flags
5069 flags
= buf
[l
+ 13] & 0x3f;
5073 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
5075 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
5078 if (rule
->src_wild
!= INADDR_BROADCAST
&&
5079 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
5082 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
5083 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
5088 if (!rule
->frag
|| rule
->action
== FILTER_ACTION_DENY
)
5096 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
5098 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
5101 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
5104 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
5105 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
5112 return rule
->action
== FILTER_ACTION_PERMIT
;