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.105 2005/05/26 12:17: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 static 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("bind_address", bind_address
, IPv4
),
117 CONFIG("peer_address", peer_address
, IPv4
),
118 CONFIG("send_garp", send_garp
, BOOL
),
119 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
120 CONFIG("throttle_buckets", num_tbfs
, INT
),
121 CONFIG("accounting_dir", accounting_dir
, STRING
),
122 CONFIG("setuid", target_uid
, INT
),
123 CONFIG("dump_speed", dump_speed
, BOOL
),
124 CONFIG("cleanup_interval", cleanup_interval
, INT
),
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 // return internal time (10ths since process startup)
194 static clockt
now(void)
198 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
201 // work out a retry time based on try number
202 // This is a straight bounded exponential backoff.
203 // Maximum re-try time is 32 seconds. (2^5).
204 clockt
backoff(uint8_t try)
206 if (try > 5) try = 5; // max backoff
207 return now() + 10 * (1 << try);
212 // Log a debug message. Typically called via the LOG macro
214 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
216 static char message
[65536] = {0};
222 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
223 ringbuffer
->tail
= 0;
224 if (ringbuffer
->tail
== ringbuffer
->head
)
225 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
226 ringbuffer
->head
= 0;
228 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
229 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
230 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
231 va_start(ap
, format
);
232 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
237 if (config
->debug
< level
) return;
239 va_start(ap
, format
);
240 vsnprintf(message
, sizeof(message
), format
, ap
);
243 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
245 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
250 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
253 const uint8_t *d
= (const uint8_t *) data
;
255 if (config
->debug
< level
) return;
257 // No support for _log_hex to syslog
260 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
261 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
263 for (i
= 0; i
< maxsize
; )
265 fprintf(log_stream
, "%4X: ", i
);
266 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
268 fprintf(log_stream
, "%02X ", d
[j
]);
270 fputs(": ", log_stream
);
273 for (; j
< i
+ 16; j
++)
275 fputs(" ", log_stream
);
277 fputs(": ", log_stream
);
280 fputs(" ", log_stream
);
281 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
283 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
284 fputc(d
[j
], log_stream
);
286 fputc('.', log_stream
);
289 fputs(" ", log_stream
);
293 fputs("\n", log_stream
);
297 setbuf(log_stream
, NULL
);
301 // initialise the random generator
302 static void initrandom(char *source
)
304 static char path
[sizeof(config
->random_device
)] = "*undefined*";
306 // reinitialise only if we are forced to do so or if the config has changed
307 if (source
&& !strncmp(path
, source
, sizeof(path
)))
310 // close previous source, if any
311 if (rand_fd
>= 0) close(rand_fd
);
318 snprintf(path
, sizeof(path
), "%s", source
);
322 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
324 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
325 path
, strerror(errno
));
329 // no source: seed prng
331 unsigned seed
= time_now
^ getpid();
332 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
337 // fill buffer with random data
338 void random_data(uint8_t *buf
, int len
)
345 n
= read(rand_fd
, buf
, len
);
346 if (n
>= len
) return;
351 LOG(0, 0, 0, "Error reading from random source: %s\n",
354 // fall back to rand()
362 // append missing data
364 // not using the low order bits from the prng stream
365 buf
[n
++] = (rand() >> 4) & 0xff;
370 // This adds it to the routing table, advertises it
371 // via BGP if enabled, and stuffs it into the
372 // 'sessionbyip' cache.
374 // 'ip' and 'mask' must be in _host_ order.
376 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
381 if (!mask
) mask
= 0xffffffff;
383 ip
&= mask
; // Force the ip to be the first one in the route.
385 memset(&r
, 0, sizeof(r
));
386 r
.rt_dev
= config
->tundevice
;
387 r
.rt_dst
.sa_family
= AF_INET
;
388 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
389 r
.rt_gateway
.sa_family
= AF_INET
;
390 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
391 r
.rt_genmask
.sa_family
= AF_INET
;
392 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
393 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
395 r
.rt_flags
|= RTF_GATEWAY
;
396 else if (mask
== 0xffffffff)
397 r
.rt_flags
|= RTF_HOST
;
399 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
400 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
401 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
403 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
404 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
408 bgp_add_route(htonl(ip
), htonl(mask
));
410 bgp_del_route(htonl(ip
), htonl(mask
));
413 // Add/Remove the IPs to the 'sessionbyip' cache.
414 // Note that we add the zero address in the case of
415 // a network route. Roll on CIDR.
417 // Note that 's == 0' implies this is the address pool.
418 // We still cache it here, because it will pre-fill
419 // the malloc'ed tree.
423 if (!add
) // Are we deleting a route?
424 s
= 0; // Caching the session as '0' is the same as uncaching.
426 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
431 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
434 char ipv6addr
[INET6_ADDRSTRLEN
];
438 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
442 memset(&rt
, 0, sizeof(rt
));
444 memcpy(&rt
.rtmsg_dst
, &ip
, sizeof(struct in6_addr
));
445 rt
.rtmsg_dst_len
= prefixlen
;
447 rt
.rtmsg_flags
= RTF_UP
;
448 rt
.rtmsg_ifindex
= tunidx
;
450 LOG(1, 0, 0, "Route %s %s/%d\n",
452 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
455 if (ioctl(ifr6fd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &rt
) < 0)
456 LOG(0, 0, 0, "route6set() error in ioctl: %s\n",
459 // FIXME: need to add BGP routing (RFC2858)
463 if (!add
) // Are we deleting a route?
464 s
= 0; // Caching the session as '0' is the same as uncaching.
466 cache_ipv6map(ip
, prefixlen
, s
);
472 // defined in linux/ipv6.h, but tricky to include from user-space
473 // TODO: move routing to use netlink rather than ioctl
475 struct in6_addr ifr6_addr
;
476 __u32 ifr6_prefixlen
;
477 unsigned int ifr6_ifindex
;
481 // Set up TUN interface
482 static void inittun(void)
485 struct in6_ifreq ifr6
;
486 struct sockaddr_in sin
= {0};
487 memset(&ifr
, 0, sizeof(ifr
));
488 ifr
.ifr_flags
= IFF_TUN
;
490 tunfd
= open(TUNDEVICE
, O_RDWR
);
493 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
497 int flags
= fcntl(tunfd
, F_GETFL
, 0);
498 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
500 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
502 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
505 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
506 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
507 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
509 sin
.sin_family
= AF_INET
;
510 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
511 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
513 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
515 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
518 /* Bump up the qlen to deal with bursts from the network */
520 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
522 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
525 ifr
.ifr_flags
= IFF_UP
;
526 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
528 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
531 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
533 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno
));
536 tunidx
= ifr
.ifr_ifindex
;
538 // Only setup IPv6 on the tun device if we have a configured prefix
539 if (config
->ipv6_prefix
.s6_addr
[0] > 0) {
540 ifr6fd
= socket(PF_INET6
, SOCK_DGRAM
, 0);
542 // Link local address is FE80::1
543 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
544 ifr6
.ifr6_addr
.s6_addr
[0] = 0xFE;
545 ifr6
.ifr6_addr
.s6_addr
[1] = 0x80;
546 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
547 ifr6
.ifr6_prefixlen
= 64;
548 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
549 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
551 LOG(0, 0, 0, "Error setting tun IPv6 link local address:"
552 " %s\n", strerror(errno
));
555 // Global address is prefix::1
556 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
557 ifr6
.ifr6_addr
= config
->ipv6_prefix
;
558 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
559 ifr6
.ifr6_prefixlen
= 64;
560 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
561 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
563 LOG(0, 0, 0, "Error setting tun IPv6 global address: %s\n",
570 static void initudp(void)
573 struct sockaddr_in addr
;
576 memset(&addr
, 0, sizeof(addr
));
577 addr
.sin_family
= AF_INET
;
578 addr
.sin_port
= htons(L2TPPORT
);
579 addr
.sin_addr
.s_addr
= config
->bind_address
;
580 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
581 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
583 int flags
= fcntl(udpfd
, F_GETFL
, 0);
584 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
586 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
588 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
591 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
594 memset(&addr
, 0, sizeof(addr
));
595 addr
.sin_family
= AF_INET
;
596 addr
.sin_port
= htons(NSCTL_PORT
);
597 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
598 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
599 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
601 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
607 // Find session by IP, < 1 for not found
609 // Confusingly enough, this 'ip' must be
610 // in _network_ order. This being the common
611 // case when looking it up from IP packet headers.
613 // We actually use this cache for two things.
614 // #1. For used IP addresses, this maps to the
615 // session ID that it's used by.
616 // #2. For un-used IP addresses, this maps to the
617 // index into the pool table that contains that
621 static int lookup_ipmap(in_addr_t ip
)
623 uint8_t *a
= (uint8_t *) &ip
;
624 uint8_t **d
= (uint8_t **) ip_hash
;
626 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
627 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
628 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
630 return (int) (intptr_t) d
[(size_t) *a
];
633 static int lookup_ipv6map(struct in6_addr ip
)
635 struct ipv6radix
*curnode
;
638 char ipv6addr
[INET6_ADDRSTRLEN
];
640 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
644 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
646 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
651 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
652 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
659 sessionidt
sessionbyip(in_addr_t ip
)
661 int s
= lookup_ipmap(ip
);
664 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
665 return (sessionidt
) s
;
670 sessionidt
sessionbyipv6(struct in6_addr ip
)
673 CSTAT(sessionbyipv6
);
675 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
676 (ip
.s6_addr
[0] == 0xFE && ip
.s6_addr
[1] == 0x80 &&
677 (ip
.s6_addr16
[1] == ip
.s6_addr16
[2] == ip
.s6_addr16
[3] == 0))) {
678 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
680 s
= lookup_ipv6map(ip
);
683 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
690 // Take an IP address in HOST byte order and
691 // add it to the sessionid by IP cache.
693 // (It's actually cached in network order)
695 static void cache_ipmap(in_addr_t ip
, int s
)
697 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
698 uint8_t *a
= (uint8_t *) &nip
;
699 uint8_t **d
= (uint8_t **) ip_hash
;
702 for (i
= 0; i
< 3; i
++)
704 if (!d
[(size_t) a
[i
]])
706 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof(void *))))
710 d
= (uint8_t **) d
[(size_t) a
[i
]];
713 d
[(size_t) a
[3]] = (uint8_t *) (intptr_t) s
;
716 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
719 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
720 // else a map to an ip pool index.
723 static void uncache_ipmap(in_addr_t ip
)
725 cache_ipmap(ip
, 0); // Assign it to the NULL session.
728 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, int s
)
732 struct ipv6radix
*curnode
;
733 char ipv6addr
[INET6_ADDRSTRLEN
];
735 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
737 bytes
= prefixlen
>> 3;
740 if (curnode
->branch
== NULL
)
742 if (!(curnode
->branch
= calloc(256,
743 sizeof (struct ipv6radix
))))
746 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
753 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
754 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
758 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
759 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
765 // CLI list to dump current ipcache.
767 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
769 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
773 if (CLI_HELP_REQUESTED
)
774 return CLI_HELP_NO_ARGS
;
776 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
778 for (i
= 0; i
< 256; ++i
)
783 for (j
= 0; j
< 256; ++j
)
788 for (k
= 0; k
< 256; ++k
)
793 for (l
= 0; l
< 256; ++l
)
797 cli_print(cli
, "%7d %d.%d.%d.%d", (int) (intptr_t) g
[l
], i
, j
, k
, l
);
803 cli_print(cli
, "%d entries in cache", count
);
808 // Find session by username, 0 for not found
809 // walled garden users aren't authenticated, so the username is
810 // reasonably useless. Ignore them to avoid incorrect actions
812 // This is VERY inefficent. Don't call it often. :)
814 sessionidt
sessionbyuser(char *username
)
817 CSTAT(sessionbyuser
);
819 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
821 if (!session
[s
].opened
)
824 if (session
[s
].walled_garden
)
825 continue; // Skip walled garden users.
827 if (!strncmp(session
[s
].user
, username
, 128))
831 return 0; // Not found.
834 void send_garp(in_addr_t ip
)
840 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
843 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
846 memset(&ifr
, 0, sizeof(ifr
));
847 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
848 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
850 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
854 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
855 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
857 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
862 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
865 static sessiont
*sessiontbysessionidt(sessionidt s
)
867 if (!s
|| s
>= MAXSESSION
) return NULL
;
871 static sessionidt
sessionidtbysessiont(sessiont
*s
)
873 sessionidt val
= s
-session
;
874 if (s
< session
|| val
>= MAXSESSION
) return 0;
878 // actually send a control message for a specific tunnel
879 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
881 struct sockaddr_in addr
;
887 static int backtrace_count
= 0;
888 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
889 STAT(tunnel_tx_errors
);
890 log_backtrace(backtrace_count
, 5)
896 static int backtrace_count
= 0;
897 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
898 log_backtrace(backtrace_count
, 5)
899 STAT(tunnel_tx_errors
);
903 memset(&addr
, 0, sizeof(addr
));
904 addr
.sin_family
= AF_INET
;
905 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
906 addr
.sin_port
= htons(tunnel
[t
].port
);
908 // sequence expected, if sequence in message
909 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
911 // If this is a control message, deal with retries
914 tunnel
[t
].last
= time_now
; // control message sent
915 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
916 if (tunnel
[t
].try > 1)
918 STAT(tunnel_retries
);
919 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
923 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
925 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
926 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
927 STAT(tunnel_tx_errors
);
931 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
932 STAT(tunnel_tx_packets
);
933 INC_STAT(tunnel_tx_bytes
, l
);
937 // Tiny helper function to write data to
940 int tun_write(uint8_t * data
, int size
)
942 return write(tunfd
, data
, size
);
945 // process outgoing (to tunnel) IP
947 static void processipout(uint8_t * buf
, int len
)
954 char *data
= buf
; // Keep a copy of the originals.
957 uint8_t b
[MAXETHER
+ 20];
961 if (len
< MIN_IP_SIZE
)
963 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
969 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
974 // Skip the tun header
978 // Got an IP header now
979 if (*(uint8_t *)(buf
) >> 4 != 4)
981 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
985 ip
= *(uint32_t *)(buf
+ 16);
986 if (!(s
= sessionbyip(ip
)))
988 // Is this a packet for a session that doesn't exist?
989 static int rate
= 0; // Number of ICMP packets we've sent this second.
990 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
992 if (last
!= time_now
)
998 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1000 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1001 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
1005 t
= session
[s
].tunnel
;
1008 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1009 if (config
->max_packets
> 0)
1011 if (sess_local
[s
].last_packet_out
== TIME
)
1013 int max
= config
->max_packets
;
1015 // All packets for throttled sessions are handled by the
1016 // master, so further limit by using the throttle rate.
1017 // A bit of a kludge, since throttle rate is in kbps,
1018 // but should still be generous given our average DSL
1019 // packet size is 200 bytes: a limit of 28kbps equates
1020 // to around 180 packets per second.
1021 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1022 max
= sp
->throttle_out
;
1024 if (++sess_local
[s
].packets_out
> max
)
1026 sess_local
[s
].packets_dropped
++;
1032 if (sess_local
[s
].packets_dropped
)
1034 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1035 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1036 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1037 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1041 sess_local
[s
].last_packet_out
= TIME
;
1042 sess_local
[s
].packets_out
= 1;
1043 sess_local
[s
].packets_dropped
= 0;
1047 // run access-list if any
1048 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1053 // Are we throttling this session?
1054 if (config
->cluster_iam_master
)
1055 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1057 master_throttle_packet(sp
->tbf_out
, data
, size
);
1060 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1062 // We are walled-gardening this
1063 master_garden_packet(s
, data
, size
);
1067 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1069 // Add on L2TP header
1071 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
1073 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1076 // Snooping this session, send it to intercept box
1077 if (sp
->snoop_ip
&& sp
->snoop_port
)
1078 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1080 sp
->cout
+= len
; // byte count
1081 sp
->total_cout
+= len
; // byte count
1084 sess_local
[s
].cout
+= len
; // To send to master..
1087 // process outgoing (to tunnel) IPv6
1089 static void processipv6out(uint8_t * buf
, int len
)
1095 struct in6_addr ip6
;
1097 char *data
= buf
; // Keep a copy of the originals.
1100 uint8_t b
[MAXETHER
+ 20];
1102 CSTAT(processipv6out
);
1104 if (len
< MIN_IP_SIZE
)
1106 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1107 STAT(tunnel_tx_errors
);
1110 if (len
>= MAXETHER
)
1112 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1113 STAT(tunnel_tx_errors
);
1117 // Skip the tun header
1121 // Got an IP header now
1122 if (*(uint8_t *)(buf
) >> 4 != 6)
1124 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1128 ip6
= *(struct in6_addr
*)(buf
+24);
1129 s
= sessionbyipv6(ip6
);
1133 ip
= *(uint32_t *)(buf
+ 32);
1134 s
= sessionbyip(ip
);
1139 // Is this a packet for a session that doesn't exist?
1140 static int rate
= 0; // Number of ICMP packets we've sent this second.
1141 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1143 if (last
!= time_now
)
1149 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1151 // FIXME: Should send icmp6 host unreachable
1155 t
= session
[s
].tunnel
;
1158 // FIXME: add DoS prevention/filters?
1162 // Are we throttling this session?
1163 if (config
->cluster_iam_master
)
1164 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1166 master_throttle_packet(sp
->tbf_out
, data
, size
);
1169 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1171 // We are walled-gardening this
1172 master_garden_packet(s
, data
, size
);
1176 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1178 // Add on L2TP header
1180 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIPV6
);
1182 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1185 // Snooping this session, send it to intercept box
1186 if (sp
->snoop_ip
&& sp
->snoop_port
)
1187 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1189 sp
->cout
+= len
; // byte count
1190 sp
->total_cout
+= len
; // byte count
1193 sess_local
[s
].cout
+= len
; // To send to master..
1197 // Helper routine for the TBF filters.
1198 // Used to send queued data in to the user!
1200 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1206 uint8_t b
[MAXETHER
+ 20];
1208 if (len
< 0 || len
> MAXETHER
)
1210 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1214 // Skip the tun header
1218 ip
= *(in_addr_t
*)(buf
+ 16);
1223 t
= session
[s
].tunnel
;
1226 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1228 // Add on L2TP header
1230 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
1232 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1235 // Snooping this session.
1236 if (sp
->snoop_ip
&& sp
->snoop_port
)
1237 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1239 sp
->cout
+= len
; // byte count
1240 sp
->total_cout
+= len
; // byte count
1243 sess_local
[s
].cout
+= len
; // To send to master..
1246 // add an AVP (16 bit)
1247 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1249 uint16_t l
= (m
? 0x8008 : 0x0008);
1250 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1251 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1252 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1253 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1257 // add an AVP (32 bit)
1258 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1260 uint16_t l
= (m
? 0x800A : 0x000A);
1261 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1262 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1263 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1264 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1268 // add an AVP (string)
1269 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1271 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1272 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1273 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1274 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1275 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1276 c
->length
+= 6 + strlen(val
);
1280 static void controlb(controlt
* c
, uint16_t avp
, char *val
, unsigned int len
, uint8_t m
)
1282 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1283 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1284 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1285 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1286 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1287 c
->length
+= 6 + len
;
1290 // new control connection
1291 static controlt
*controlnew(uint16_t mtype
)
1295 c
= malloc(sizeof(controlt
));
1299 controlfree
= c
->next
;
1303 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1305 control16(c
, 0, mtype
, 1);
1309 // send zero block if nothing is waiting
1311 static void controlnull(tunnelidt t
)
1314 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1317 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1318 *(uint16_t *) (buf
+ 2) = htons(12); // length
1319 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1320 *(uint16_t *) (buf
+ 6) = htons(0); // session
1321 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1322 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1323 tunnelsend(buf
, 12, t
);
1326 // add a control message to a tunnel, and send if within window
1327 static void controladd(controlt
* c
, tunnelidt t
, sessionidt far
)
1329 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1330 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1331 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1332 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1333 tunnel
[t
].ns
++; // advance sequence
1334 // link in message in to queue
1335 if (tunnel
[t
].controlc
)
1336 tunnel
[t
].controle
->next
= c
;
1338 tunnel
[t
].controls
= c
;
1340 tunnel
[t
].controle
= c
;
1341 tunnel
[t
].controlc
++;
1343 // send now if space in window
1344 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1346 tunnel
[t
].try = 0; // first send
1347 tunnelsend(c
->buf
, c
->length
, t
);
1352 // Throttle or Unthrottle a session
1354 // Throttle the data from/to through a session to no more than
1355 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1358 // If either value is -1, the current value is retained for that
1361 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1363 if (!session
[s
].opened
)
1364 return; // No-one home.
1366 if (!*session
[s
].user
)
1367 return; // User not logged in
1371 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1372 if (session
[s
].tbf_in
)
1373 free_tbf(session
[s
].tbf_in
);
1376 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1378 session
[s
].tbf_in
= 0;
1380 session
[s
].throttle_in
= rate_in
;
1385 int bytes
= rate_out
* 1024 / 8;
1386 if (session
[s
].tbf_out
)
1387 free_tbf(session
[s
].tbf_out
);
1390 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1392 session
[s
].tbf_out
= 0;
1394 session
[s
].throttle_out
= rate_out
;
1398 // add/remove filters from session (-1 = no change)
1399 static void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1401 if (!session
[s
].opened
)
1402 return; // No-one home.
1404 if (!*session
[s
].user
)
1405 return; // User not logged in
1408 if (filter_in
> MAXFILTER
) filter_in
= -1;
1409 if (filter_out
> MAXFILTER
) filter_out
= -1;
1410 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1411 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1415 if (session
[s
].filter_in
)
1416 ip_filters
[session
[s
].filter_in
- 1].used
--;
1419 ip_filters
[filter_in
- 1].used
++;
1421 session
[s
].filter_in
= filter_in
;
1424 if (filter_out
>= 0)
1426 if (session
[s
].filter_out
)
1427 ip_filters
[session
[s
].filter_out
- 1].used
--;
1430 ip_filters
[filter_out
- 1].used
++;
1432 session
[s
].filter_out
= filter_out
;
1436 // start tidy shutdown of session
1437 void sessionshutdown(sessionidt s
, char *reason
, int result
, int error
)
1439 int walled_garden
= session
[s
].walled_garden
;
1442 CSTAT(sessionshutdown
);
1444 if (!session
[s
].opened
)
1446 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1447 return; // not a live session
1450 if (!session
[s
].die
)
1452 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1453 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1454 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1457 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1459 // RADIUS Stop message
1460 uint16_t r
= sess_local
[s
].radius
;
1466 // stop, if not already trying
1467 if (radius
[r
].state
!= RADIUSSTOP
)
1468 radiussend(r
, RADIUSSTOP
);
1471 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1473 // Save counters to dump to accounting file
1474 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1475 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1479 { // IP allocated, clear and unroute
1482 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1484 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1485 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1488 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1489 session
[s
].route
[r
].ip
= 0;
1492 if (session
[s
].ip_pool_index
== -1) // static ip
1494 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1500 // unroute IPv6, if setup
1501 if (session
[s
].flags
& SF_IPV6_ROUTED
)
1502 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1505 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1506 throttle_session(s
, 0, 0);
1510 controlt
*c
= controlnew(14); // sending CDN
1514 *(uint16_t *) buf
= htons(result
);
1515 *(uint16_t *) (buf
+2) = htons(error
);
1516 controlb(c
, 1, buf
, 4, 1);
1519 control16(c
, 1, result
, 1);
1521 control16(c
, 14, s
, 1); // assigned session (our end)
1522 controladd(c
, session
[s
].tunnel
, session
[s
].far
); // send the message
1525 if (!session
[s
].die
)
1526 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1528 // update filter refcounts
1529 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1530 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1532 cluster_send_session(s
);
1535 void sendipcp(tunnelidt t
, sessionidt s
)
1537 uint8_t buf
[MAXCONTROL
];
1538 uint16_t r
= sess_local
[s
].radius
;
1548 sessionshutdown(s
, "No free RADIUS sessions for IPCP", 3, 0);
1552 if (radius
[r
].state
!= RADIUSIPCP
)
1554 radius
[r
].state
= RADIUSIPCP
;
1558 radius
[r
].retry
= backoff(radius
[r
].try++);
1559 if (radius
[r
].try > 10)
1561 radiusclear(r
, s
); // Clear radius session.
1562 sessionshutdown(s
, "No reply to IPCP.", 3, 0);
1566 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1570 q
[1] = r
>> RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1571 *(uint16_t *) (q
+ 2) = htons(10);
1574 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1575 config
->bind_address
? config
->bind_address
:
1576 my_address
; // send my IP
1578 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1579 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1581 // If we have an IPv6 prefix length configured, assume we should
1582 // try to negotiate an IPv6 session as well. Unless we've had a
1583 // (N)ACK for IPV6CP.
1584 if (config
->ipv6_prefix
.s6_addr
[0] > 0 &&
1585 !(session
[s
].flags
& SF_IPV6CP_ACKED
) &&
1586 !(session
[s
].flags
& SF_IPV6_NACKED
))
1588 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPV6CP
);
1592 q
[1] = r
>> RADIUS_SHIFT
; // ID, don't care, we
1593 // only send one type
1595 *(uint16_t *) (q
+ 2) = htons(14);
1598 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
1599 *(uint32_t *) (q
+ 10) = 0;
1602 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
1606 static void sessionclear(sessionidt s
)
1608 memset(&session
[s
], 0, sizeof(session
[s
]));
1609 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
1610 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
1612 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1613 session
[s
].next
= sessionfree
;
1617 // kill a session now
1618 void sessionkill(sessionidt s
, char *reason
)
1623 if (!session
[s
].opened
) // not alive
1626 if (session
[s
].next
)
1628 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%d)\n", session
[s
].next
);
1632 session
[s
].die
= TIME
;
1633 sessionshutdown(s
, reason
, 3, 0); // close radius/routes, etc.
1634 if (sess_local
[s
].radius
)
1635 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
1637 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1639 cluster_send_session(s
);
1642 static void tunnelclear(tunnelidt t
)
1645 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1646 tunnel
[t
].state
= TUNNELFREE
;
1649 // kill a tunnel now
1650 static void tunnelkill(tunnelidt t
, char *reason
)
1657 tunnel
[t
].state
= TUNNELDIE
;
1659 // free control messages
1660 while ((c
= tunnel
[t
].controls
))
1662 controlt
* n
= c
->next
;
1663 tunnel
[t
].controls
= n
;
1664 tunnel
[t
].controlc
--;
1665 c
->next
= controlfree
;
1669 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1670 if (session
[s
].tunnel
== t
)
1671 sessionkill(s
, reason
);
1675 LOG(1, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1676 cli_tunnel_actions
[t
].action
= 0;
1677 cluster_send_tunnel(t
);
1680 // shut down a tunnel cleanly
1681 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
1685 CSTAT(tunnelshutdown
);
1687 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1689 // never set up, can immediately kill
1690 tunnelkill(t
, reason
);
1693 LOG(1, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1696 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1697 if (session
[s
].tunnel
== t
)
1698 sessionshutdown(s
, reason
, 3, 0);
1700 tunnel
[t
].state
= TUNNELDIE
;
1701 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
1702 cluster_send_tunnel(t
);
1703 // TBA - should we wait for sessions to stop?
1706 controlt
*c
= controlnew(4); // sending StopCCN
1711 *(uint16_t *) buf
= htons(result
);
1712 *(uint16_t *) (buf
+2) = htons(error
);
1715 int m
= strlen(msg
);
1716 if (m
+ 4 > sizeof(buf
))
1717 m
= sizeof(buf
) - 4;
1719 memcpy(buf
+4, msg
, m
);
1723 controlb(c
, 1, buf
, l
, 1);
1726 control16(c
, 1, result
, 1);
1728 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1729 controladd(c
, t
, 0); // send the message
1733 // read and process packet on tunnel (UDP)
1734 void processudp(uint8_t * buf
, int len
, struct sockaddr_in
*addr
)
1736 char *chapresponse
= NULL
;
1737 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1738 uint8_t *p
= buf
+ 2;
1745 LOG_HEX(5, "UDP Data", buf
, len
);
1746 STAT(tunnel_rx_packets
);
1747 INC_STAT(tunnel_rx_bytes
, len
);
1750 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
1751 STAT(tunnel_rx_errors
);
1754 if ((buf
[1] & 0x0F) != 2)
1756 LOG(1, 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1757 STAT(tunnel_rx_errors
);
1762 l
= ntohs(*(uint16_t *) p
);
1765 t
= ntohs(*(uint16_t *) p
);
1767 s
= ntohs(*(uint16_t *) p
);
1769 if (s
>= MAXSESSION
)
1771 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
1772 STAT(tunnel_rx_errors
);
1777 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
1778 STAT(tunnel_rx_errors
);
1783 ns
= ntohs(*(uint16_t *) p
);
1785 nr
= ntohs(*(uint16_t *) p
);
1790 uint16_t o
= ntohs(*(uint16_t *) p
);
1795 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
1796 STAT(tunnel_rx_errors
);
1802 uint16_t message
= 0xFFFF; // message type
1804 uint8_t mandatory
= 0;
1805 uint8_t authtype
= 0; // proxy auth type
1806 uint16_t asession
= 0; // assigned session
1807 uint32_t amagic
= 0; // magic number
1808 uint8_t aflags
= 0; // flags from last LCF
1809 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1810 char called
[MAXTEL
] = ""; // called number
1811 char calling
[MAXTEL
] = ""; // calling number
1813 if (!config
->cluster_iam_master
)
1815 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1819 // control messages must have bits 0x80|0x40|0x08
1820 // (type, length and sequence) set, and bits 0x02|0x01
1821 // (offset and priority) clear
1822 if ((*buf
& 0xCB) != 0xC8)
1824 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
1825 STAT(tunnel_rx_errors
);
1829 // check for duplicate tunnel open message
1835 // Is this a duplicate of the first packet? (SCCRQ)
1837 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1839 if (tunnel
[i
].state
!= TUNNELOPENING
||
1840 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
1841 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1844 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
1849 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1850 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1852 // if no tunnel specified, assign one
1855 if (!(t
= new_tunnel()))
1857 LOG(1, 0, 0, "No more tunnels\n");
1858 STAT(tunnel_overflow
);
1862 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
1863 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1864 tunnel
[t
].window
= 4; // default window
1865 STAT(tunnel_created
);
1866 LOG(1, 0, t
, " New tunnel from %s:%u ID %d\n",
1867 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
1870 // If the 'ns' just received is not the 'nr' we're
1871 // expecting, just send an ack and drop it.
1873 // if 'ns' is less, then we got a retransmitted packet.
1874 // if 'ns' is greater than missed a packet. Either way
1875 // we should ignore it.
1876 if (ns
!= tunnel
[t
].nr
)
1878 // is this the sequence we were expecting?
1879 STAT(tunnel_rx_errors
);
1880 LOG(1, 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n",
1881 t
, ns
, tunnel
[t
].nr
);
1883 if (l
) // Is this not a ZLB?
1888 // This is used to time out old tunnels
1889 tunnel
[t
].lastrec
= time_now
;
1891 // check sequence of this message
1893 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1894 // some to clear maybe?
1895 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1897 controlt
*c
= tunnel
[t
].controls
;
1898 tunnel
[t
].controls
= c
->next
;
1899 tunnel
[t
].controlc
--;
1900 c
->next
= controlfree
;
1903 tunnel
[t
].try = 0; // we have progress
1906 // receiver advance (do here so quoted correctly in any sends below)
1907 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1908 if (skip
< 0) skip
= 0;
1909 if (skip
< tunnel
[t
].controlc
)
1911 // some control packets can now be sent that were previous stuck out of window
1912 int tosend
= tunnel
[t
].window
- skip
;
1913 controlt
*c
= tunnel
[t
].controls
;
1921 tunnel
[t
].try = 0; // first send
1922 tunnelsend(c
->buf
, c
->length
, t
);
1927 if (!tunnel
[t
].controlc
)
1928 tunnel
[t
].retry
= 0; // caught up
1931 { // if not a null message
1937 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
1939 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
1945 LOG(1, s
, t
, "Invalid length in AVP\n");
1946 STAT(tunnel_rx_errors
);
1951 if (flags
& 0x3C) // reserved bits, should be clear
1953 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1955 result
= 2; // general error
1956 error
= 3; // reserved field non-zero
1961 if (*(uint16_t *) (b
))
1963 LOG(2, s
, t
, "Unknown AVP vendor %d\n", ntohs(*(uint16_t *) (b
)));
1965 result
= 2; // general error
1966 error
= 6; // generic vendor-specific error
1967 msg
= "unsupported vendor-specific";
1971 mtype
= ntohs(*(uint16_t *) (b
));
1979 // handle hidden AVPs
1980 if (!*config
->l2tpsecret
)
1982 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1984 result
= 2; // general error
1985 error
= 6; // generic vendor-specific error
1986 msg
= "secret not specified";
1989 if (!session
[s
].random_vector_length
)
1991 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
1993 result
= 2; // general error
1994 error
= 6; // generic
1995 msg
= "no random vector";
2000 LOG(2, s
, t
, "Short hidden AVP.\n");
2002 result
= 2; // general error
2003 error
= 2; // length is wrong
2008 LOG(4, s
, t
, "Hidden AVP\n");
2011 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2013 orig_len
= ntohs(*(uint16_t *) b
);
2014 if (orig_len
> n
+ 2)
2016 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2020 result
= 2; // general error
2021 error
= 2; // length is wrong
2030 LOG(4, s
, t
, " AVP %d (%s) len %d\n", mtype
, avp_name(mtype
), n
);
2033 case 0: // message type
2034 message
= ntohs(*(uint16_t *) b
);
2035 mandatory
= flags
& 0x80;
2036 LOG(4, s
, t
, " Message type = %d (%s)\n", *b
, l2tp_message_type(message
));
2038 case 1: // result code
2040 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2041 const char* resdesc
= "(unknown)";
2044 resdesc
= stopccn_result_code(rescode
);
2046 else if (message
== 14)
2048 resdesc
= cdn_result_code(rescode
);
2051 LOG(4, s
, t
, " Result Code %d: %s\n", rescode
, resdesc
);
2054 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2055 LOG(4, s
, t
, " Error Code %d: %s\n", errcode
, error_code(errcode
));
2058 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2063 case 2: // protocol version
2065 version
= ntohs(*(uint16_t *) (b
));
2066 LOG(4, s
, t
, " Protocol version = %d\n", version
);
2067 if (version
&& version
!= 0x0100)
2068 { // allow 0.0 and 1.0
2069 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2071 result
= 5; // unspported protocol version
2072 error
= 0x0100; // supported version
2078 case 3: // framing capabilities
2079 // LOG(4, s, t, "Framing capabilities\n");
2081 case 4: // bearer capabilities
2082 // LOG(4, s, t, "Bearer capabilities\n");
2084 case 5: // tie breaker
2085 // We never open tunnels, so we don't care about tie breakers
2086 // LOG(4, s, t, "Tie breaker\n");
2088 case 6: // firmware revision
2089 // LOG(4, s, t, "Firmware revision\n");
2091 case 7: // host name
2092 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2093 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2094 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2095 // TBA - to send to RADIUS
2097 case 8: // vendor name
2098 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2099 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2100 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2102 case 9: // assigned tunnel
2103 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2104 LOG(4, s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
2106 case 10: // rx window
2107 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2108 if (!tunnel
[t
].window
)
2109 tunnel
[t
].window
= 1; // window of 0 is silly
2110 LOG(4, s
, t
, " rx window = %d\n", tunnel
[t
].window
);
2112 case 11: // Challenge
2114 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2115 build_chap_response(b
, 2, n
, &chapresponse
);
2118 case 13: // Response
2119 // Why did they send a response? We never challenge.
2120 LOG(2, s
, t
, " received unexpected challenge response\n");
2123 case 14: // assigned session
2124 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2125 LOG(4, s
, t
, " assigned session = %d\n", asession
);
2127 case 15: // call serial number
2128 LOG(4, s
, t
, " call serial number = %d\n", ntohl(*(uint32_t *)b
));
2130 case 18: // bearer type
2131 LOG(4, s
, t
, " bearer type = %d\n", ntohl(*(uint32_t *)b
));
2134 case 19: // framing type
2135 LOG(4, s
, t
, " framing type = %d\n", ntohl(*(uint32_t *)b
));
2138 case 21: // called number
2139 memset(called
, 0, sizeof(called
));
2140 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2141 LOG(4, s
, t
, " Called <%s>\n", called
);
2143 case 22: // calling number
2144 memset(calling
, 0, sizeof(calling
));
2145 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2146 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2150 case 24: // tx connect speed
2153 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2157 // AS5300s send connect speed as a string
2159 memset(tmp
, 0, sizeof(tmp
));
2160 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2161 session
[s
].tx_connect_speed
= atol(tmp
);
2163 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2165 case 38: // rx connect speed
2168 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2172 // AS5300s send connect speed as a string
2174 memset(tmp
, 0, sizeof(tmp
));
2175 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2176 session
[s
].rx_connect_speed
= atol(tmp
);
2178 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2180 case 25: // Physical Channel ID
2182 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2183 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2186 case 29: // Proxy Authentication Type
2188 uint16_t atype
= ntohs(*(uint16_t *)b
);
2189 LOG(4, s
, t
, " Proxy Auth Type %d (%s)\n", atype
, auth_type(atype
));
2191 authtype
= AUTHCHAP
;
2192 else if (atype
== 3)
2197 case 30: // Proxy Authentication Name
2200 memset(authname
, 0, sizeof(authname
));
2201 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2202 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2206 case 31: // Proxy Authentication Challenge
2208 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2209 if (sess_local
[s
].radius
)
2210 memcpy(radius
[sess_local
[s
].radius
].auth
, b
, 16);
2213 case 32: // Proxy Authentication ID
2215 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2216 LOG(4, s
, t
, " Proxy Auth ID (%d)\n", authid
);
2217 if (sess_local
[s
].radius
)
2218 radius
[sess_local
[s
].radius
].id
= authid
;
2221 case 33: // Proxy Authentication Response
2222 LOG(4, s
, t
, " Proxy Auth Response\n");
2224 case 27: // last sent lcp
2225 { // find magic number
2226 uint8_t *p
= b
, *e
= p
+ n
;
2227 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2229 if (*p
== 5 && p
[1] == 6) // Magic-Number
2230 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2231 else if (*p
== 3 && p
[1] == 4 && *(uint16_t *) (p
+ 2) == htons(PPPPAP
)) // Authentication-Protocol (PAP)
2233 else if (*p
== 3 && p
[1] == 5 && *(uint16_t *) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol (CHAP)
2234 authtype
= AUTHCHAP
;
2235 else if (*p
== 7) // Protocol-Field-Compression
2236 aflags
|= SESSIONPFC
;
2237 else if (*p
== 8) // Address-and-Control-Field-Compression
2238 aflags
|= SESSIONACFC
;
2243 case 28: // last recv lcp confreq
2245 case 26: // Initial Received LCP CONFREQ
2247 case 39: // seq required - we control it as an LNS anyway...
2249 case 36: // Random Vector
2250 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2251 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2252 memcpy(session
[s
].random_vector
, b
, n
);
2253 session
[s
].random_vector_length
= n
;
2257 static char e
[] = "unknown AVP 0xXXXX";
2258 LOG(2, s
, t
, " Unknown AVP type %d\n", mtype
);
2260 result
= 2; // general error
2261 error
= 8; // unknown mandatory AVP
2262 sprintf((msg
= e
) + 14, "%04x", mtype
);
2269 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2273 case 1: // SCCRQ - Start Control Connection Request
2275 controlt
*c
= controlnew(2); // sending SCCRP
2276 control16(c
, 2, version
, 1); // protocol version
2277 control32(c
, 3, 3, 1); // framing
2278 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
2279 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2280 control16(c
, 9, t
, 1); // assigned tunnel
2281 controladd(c
, t
, 0); // send the resply
2283 tunnel
[t
].state
= TUNNELOPENING
;
2286 tunnel
[t
].state
= TUNNELOPEN
;
2289 tunnel
[t
].state
= TUNNELOPEN
;
2290 controlnull(t
); // ack
2293 controlnull(t
); // ack
2294 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2297 controlnull(t
); // simply ACK
2314 sessionfree
= session
[s
].next
;
2315 memset(&session
[s
], 0, sizeof(session
[s
]));
2317 if (s
> config
->cluster_highest_sessionid
)
2318 config
->cluster_highest_sessionid
= s
;
2320 // make a RADIUS session
2321 if ((r
= radiusnew(s
)))
2323 controlt
*c
= controlnew(11); // sending ICRP
2324 session
[s
].opened
= time_now
;
2325 session
[s
].tunnel
= t
;
2326 session
[s
].far
= asession
;
2327 session
[s
].last_packet
= time_now
;
2328 LOG(3, s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
2329 control16(c
, 14, s
, 1); // assigned session
2330 controladd(c
, t
, asession
); // send the reply
2332 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
2333 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2334 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2335 STAT(session_created
);
2340 LOG(1, s
, t
, "No free RADIUS sessions for ICRQ\n");
2345 STAT(session_overflow
);
2346 LOG(1, 0, t
, "No free sessions\n");
2350 controlt
*c
= controlnew(14); // CDN
2351 control16(c
, 1, 4, 1); // temporary lack of resources
2352 controladd(c
, session
[s
].tunnel
, asession
); // send the message
2359 if (amagic
== 0) amagic
= time_now
;
2360 session
[s
].magic
= amagic
; // set magic number
2361 session
[s
].l2tp_flags
= aflags
; // set flags received
2362 LOG(3, s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
2363 controlnull(t
); // ack
2364 // proxy authentication type is not supported
2365 if (!(config
->radius_authtypes
& authtype
))
2366 authtype
= config
->radius_authprefer
;
2369 sendlcp(t
, s
, authtype
);
2372 controlnull(t
); // ack
2373 sessionshutdown(s
, "Closed (Received CDN).", 0, 0);
2376 LOG(1, s
, t
, "Missing message type\n");
2379 STAT(tunnel_rx_errors
);
2381 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2383 LOG(1, s
, t
, "Unknown message type %d\n", message
);
2386 if (chapresponse
) free(chapresponse
);
2387 cluster_send_tunnel(t
);
2391 LOG(4, s
, t
, " Got a ZLB ack\n");
2398 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
2399 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
2400 { // HDLC address header, discard
2406 LOG(1, s
, t
, "Short ppp length %d\n", l
);
2407 STAT(tunnel_rx_errors
);
2417 prot
= ntohs(*(uint16_t *) p
);
2422 if (s
&& !session
[s
].opened
) // Is something wrong??
2424 if (!config
->cluster_iam_master
)
2426 // Pass it off to the master to deal with..
2427 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2432 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
2433 STAT(tunnel_rx_errors
);
2439 session
[s
].last_packet
= time_now
;
2440 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2441 processpap(t
, s
, p
, l
);
2443 else if (prot
== PPPCHAP
)
2445 session
[s
].last_packet
= time_now
;
2446 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2447 processchap(t
, s
, p
, l
);
2449 else if (prot
== PPPLCP
)
2451 session
[s
].last_packet
= time_now
;
2452 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2453 processlcp(t
, s
, p
, l
);
2455 else if (prot
== PPPIPCP
)
2457 session
[s
].last_packet
= time_now
;
2458 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2459 processipcp(t
, s
, p
, l
);
2461 else if (prot
== PPPIPV6CP
)
2463 if (config
->ipv6_prefix
.s6_addr
[0] > 0)
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 processipv6cp(t
, s
, p
, l
);
2471 LOG(1, s
, t
, "IPv6 not configured; ignoring IPv6CP\n");
2474 else if (prot
== PPPCCP
)
2476 session
[s
].last_packet
= time_now
;
2477 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2478 processccp(t
, s
, p
, l
);
2480 else if (prot
== PPPIP
)
2484 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
2485 return; // closing session, PPP not processed
2488 session
[s
].last_packet
= time_now
;
2489 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2491 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2495 processipin(t
, s
, p
, l
);
2497 else if (prot
== PPPIPV6
)
2499 if (!config
->ipv6_prefix
.s6_addr
[0] > 0)
2501 LOG(1, s
, t
, "IPv6 not configured; yet received IPv6 packet. Ignoring.\n");
2506 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
2507 return; // closing session, PPP not processed
2510 session
[s
].last_packet
= time_now
;
2511 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2513 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2517 processipv6in(t
, s
, p
, l
);
2521 STAT(tunnel_rx_errors
);
2522 LOG(1, s
, t
, "Unknown PPP protocol %04X\n", prot
);
2527 // read and process packet on tun
2528 static void processtun(uint8_t * buf
, int len
)
2530 LOG_HEX(5, "Receive TUN Data", buf
, len
);
2531 STAT(tun_rx_packets
);
2532 INC_STAT(tun_rx_bytes
, len
);
2540 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
2541 STAT(tun_rx_errors
);
2545 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
2546 processipout(buf
, len
);
2547 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
2548 && config
->ipv6_prefix
.s6_addr
[0] > 0)
2549 processipv6out(buf
, len
);
2555 // Maximum number of actions to complete.
2556 // This is to avoid sending out too many packets
2558 #define MAX_ACTIONS 500
2560 static int regular_cleanups(void)
2562 static sessionidt s
= 0; // Next session to check for actions on.
2566 static clockt next_acct
= 0;
2567 static clockt next_shut_acct
= 0;
2570 LOG(3, 0, 0, "Begin regular cleanup\n");
2572 for (r
= 1; r
< MAXRADIUS
; r
++)
2574 if (!radius
[r
].state
)
2576 if (radius
[r
].retry
)
2578 if (radius
[r
].retry
<= TIME
)
2581 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
2583 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
2585 // check for expired tunnels
2586 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2588 STAT(tunnel_timeout
);
2589 tunnelkill(t
, "Expired");
2592 // check for message resend
2593 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2595 // resend pending messages as timeout on reply
2596 if (tunnel
[t
].retry
<= TIME
)
2598 controlt
*c
= tunnel
[t
].controls
;
2599 uint8_t w
= tunnel
[t
].window
;
2600 tunnel
[t
].try++; // another try
2601 if (tunnel
[t
].try > 5)
2602 tunnelkill(t
, "Timeout on control message"); // game over
2606 tunnelsend(c
->buf
, c
->length
, t
);
2612 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2614 controlt
*c
= controlnew(6); // sending HELLO
2615 controladd(c
, t
, 0); // send the message
2616 LOG(3, 0, t
, "Sending HELLO message\n");
2619 // Check for tunnel changes requested from the CLI
2620 if ((a
= cli_tunnel_actions
[t
].action
))
2622 cli_tunnel_actions
[t
].action
= 0;
2623 if (a
& CLI_TUN_KILL
)
2625 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
2626 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
2633 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2636 if (s
> config
->cluster_highest_sessionid
)
2639 if (!session
[s
].opened
) // Session isn't in use
2642 // check for expired sessions
2645 if (session
[s
].die
<= TIME
)
2647 sessionkill(s
, "Expired");
2648 if (++count
>= MAX_ACTIONS
) break;
2653 if (session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2655 // IPCP has not completed yet. Resend
2656 LOG(3, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2657 sendipcp(session
[s
].tunnel
, s
);
2660 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2661 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2663 sessionshutdown(s
, "No response to LCP ECHO requests.", 3, 0);
2664 STAT(session_timeout
);
2665 if (++count
>= MAX_ACTIONS
) break;
2669 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
2670 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2672 uint8_t b
[MAXCONTROL
] = {0};
2674 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2678 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
2679 *(uint16_t *)(q
+ 2) = htons(8); // Length
2680 *(uint32_t *)(q
+ 4) = 0; // Magic Number (not supported)
2682 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2683 (int)(time_now
- session
[s
].last_packet
));
2684 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2685 if (++count
>= MAX_ACTIONS
) break;
2688 // Check for actions requested from the CLI
2689 if ((a
= cli_session_actions
[s
].action
))
2693 cli_session_actions
[s
].action
= 0;
2694 if (a
& CLI_SESS_KILL
)
2696 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2697 sessionshutdown(s
, "Requested by administrator.", 3, 0);
2698 a
= 0; // dead, no need to check for other actions
2701 if (a
& CLI_SESS_NOSNOOP
)
2703 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2704 session
[s
].snoop_ip
= 0;
2705 session
[s
].snoop_port
= 0;
2708 else if (a
& CLI_SESS_SNOOP
)
2710 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2711 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
2712 cli_session_actions
[s
].snoop_port
);
2714 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2715 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2719 if (a
& CLI_SESS_NOTHROTTLE
)
2721 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2722 throttle_session(s
, 0, 0);
2725 else if (a
& CLI_SESS_THROTTLE
)
2727 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2728 cli_session_actions
[s
].throttle_in
,
2729 cli_session_actions
[s
].throttle_out
);
2731 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2735 if (a
& CLI_SESS_NOFILTER
)
2737 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
2738 filter_session(s
, 0, 0);
2741 else if (a
& CLI_SESS_FILTER
)
2743 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
2744 cli_session_actions
[s
].filter_in
,
2745 cli_session_actions
[s
].filter_out
);
2747 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
2752 cluster_send_session(s
);
2754 if (++count
>= MAX_ACTIONS
) break;
2757 // RADIUS interim accounting
2758 if (config
->radius_accounting
&& config
->radius_interim
> 0
2759 && session
[s
].ip
&& !session
[s
].walled_garden
2760 && !sess_local
[s
].radius
// RADIUS already in progress
2761 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
)
2763 if (!(r
= radiusnew(s
)))
2765 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
2766 STAT(radius_overflow
);
2770 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
2771 session
[s
].user
, session
[s
].unique_id
);
2773 radiussend(r
, RADIUSINTERIM
);
2774 sess_local
[s
].last_interim
= time_now
;
2776 if (++count
>= MAX_ACTIONS
)
2781 if (*config
->accounting_dir
)
2783 if (next_acct
<= TIME
)
2785 // Dump accounting data
2786 next_acct
= TIME
+ ACCT_TIME
;
2787 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2790 else if (next_shut_acct
<= TIME
)
2792 // Dump accounting data for shutdown sessions
2793 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2799 if (count
>= MAX_ACTIONS
)
2800 return 1; // Didn't finish!
2802 LOG(3, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count
, config
->cleanup_interval
);
2808 // Are we in the middle of a tunnel update, or radius
2811 static int still_busy(void)
2814 static clockt last_talked
= 0;
2815 static clockt start_busy_wait
= 0;
2816 if (start_busy_wait
== 0)
2817 start_busy_wait
= TIME
;
2819 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2821 if (!tunnel
[i
].controlc
)
2824 if (last_talked
!= TIME
)
2826 LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i
);
2832 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2833 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2835 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2839 for (i
= 1; i
< MAXRADIUS
; i
++)
2841 if (radius
[i
].state
== RADIUSNULL
)
2843 if (radius
[i
].state
== RADIUSWAIT
)
2846 if (last_talked
!= TIME
)
2848 LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2857 static fd_set readset
;
2858 static int readset_n
= 0;
2860 // main loop - gets packets on tun or udp and processes them
2861 static void mainloop(void)
2866 clockt next_cluster_ping
= 0; // send initial ping immediately
2867 time_t next_clean
= time_now
+ config
->cleanup_interval
;
2869 LOG(4, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2870 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2873 FD_SET(udpfd
, &readset
);
2874 FD_SET(tunfd
, &readset
);
2875 FD_SET(controlfd
, &readset
);
2876 FD_SET(clifd
, &readset
);
2877 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2879 if (tunfd
> readset_n
) readset_n
= tunfd
;
2880 if (controlfd
> readset_n
) readset_n
= controlfd
;
2881 if (clifd
> readset_n
) readset_n
= clifd
;
2882 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2884 while (!main_quit
|| still_busy())
2890 int bgp_set
[BGP_NUM_PEERS
];
2893 if (config
->reload_config
)
2895 // Update the config state based on config settings
2899 memcpy(&r
, &readset
, sizeof(fd_set
));
2901 to
.tv_usec
= 100000; // 1/10th of a second.
2905 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2907 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2910 FD_SET(bgp_peers
[i
].sock
, &r
);
2911 if (bgp_peers
[i
].sock
> n
)
2912 n
= bgp_peers
[i
].sock
;
2917 FD_SET(bgp_peers
[i
].sock
, &w
);
2918 if (bgp_peers
[i
].sock
> n
)
2919 n
= bgp_peers
[i
].sock
;
2923 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2925 n
= select(n
+ 1, &r
, 0, 0, &to
);
2928 STAT(select_called
);
2933 if (errno
== EINTR
||
2934 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2937 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2943 struct sockaddr_in addr
;
2947 int cluster_pkts
= 0;
2950 if (FD_ISSET(controlfd
, &r
))
2952 alen
= sizeof(addr
);
2953 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
, alen
);
2958 if (config
->cluster_iam_master
)
2960 for (i
= 0; i
< config
->num_radfds
; i
++)
2962 if (FD_ISSET(radfds
[i
], &r
))
2964 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2971 if (FD_ISSET(clifd
, &r
))
2975 alen
= sizeof(addr
);
2976 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
2982 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
2988 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2990 int isr
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0;
2991 int isw
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0;
2992 bgp_process(&bgp_peers
[i
], isr
, isw
);
2998 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3001 if (FD_ISSET(udpfd
, &r
))
3003 alen
= sizeof(addr
);
3004 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3006 processudp(buf
, s
, &addr
);
3017 if (FD_ISSET(tunfd
, &r
))
3019 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3032 if (FD_ISSET(cluster_sockfd
, &r
))
3034 alen
= sizeof(addr
);
3035 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3037 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3042 FD_CLR(cluster_sockfd
, &r
);
3048 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3049 STAT(multi_read_used
);
3051 if (c
>= config
->multi_read_count
)
3053 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3054 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3056 STAT(multi_read_exceeded
);
3060 // Runs on every machine (master and slaves).
3061 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
3063 // Check to see which of the cluster is still alive..
3065 cluster_send_ping(basetime
); // Only does anything if we're a slave
3066 cluster_check_master(); // ditto.
3068 cluster_heartbeat(); // Only does anything if we're a master.
3069 cluster_check_slaves(); // ditto.
3071 master_update_counts(); // If we're a slave, send our byte counters to our master.
3073 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
3074 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
3076 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
3079 // Run token bucket filtering queue..
3080 // Only run it every 1/10th of a second.
3081 // Runs on all machines both master and slave.
3083 static clockt last_run
= 0;
3084 if (last_run
!= TIME
)
3091 /* Handle timeouts. Make sure that this gets run anyway, even if there was
3092 * something to read, else under load this will never actually run....
3095 if (config
->cluster_iam_master
&& next_clean
<= time_now
)
3097 if (regular_cleanups())
3100 next_clean
= time_now
+ 1 ; // Didn't finish. Check quickly.
3104 next_clean
= time_now
+ config
->cleanup_interval
; // Did. Move to next interval.
3109 // Are we the master and shutting down??
3110 if (config
->cluster_iam_master
)
3111 cluster_heartbeat(); // Flush any queued changes..
3113 // Ok. Notify everyone we're shutting down. If we're
3114 // the master, this will force an election.
3115 cluster_send_ping(0);
3118 // Important!!! We MUST not process any packets past this point!
3121 static void stripdomain(char *host
)
3125 if ((p
= strchr(host
, '.')))
3131 FILE *resolv
= fopen("/etc/resolv.conf", "r");
3137 while (fgets(buf
, sizeof(buf
), resolv
))
3139 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
3142 if (!isspace(buf
[6]))
3146 while (isspace(*b
)) b
++;
3151 while (*b
&& !isspace(*b
)) b
++;
3153 if (buf
[0] == 'd') // domain is canonical
3159 // first search line
3162 // hold, may be subsequent domain line
3163 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
3174 int hl
= strlen(host
);
3175 int dl
= strlen(domain
);
3176 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
3177 host
[hl
-dl
- 1] = 0;
3181 *p
= 0; // everything after first dot
3186 // Init data structures
3187 static void initdata(int optdebug
, char *optconfig
)
3191 if (!(config
= shared_malloc(sizeof(configt
))))
3193 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
3197 memset(config
, 0, sizeof(configt
));
3198 time(&config
->start_time
);
3199 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
3200 config
->debug
= optdebug
;
3201 config
->num_tbfs
= MAXTBFS
;
3202 config
->rl_rate
= 28; // 28kbps
3203 config
->cluster_master_min_adv
= 1;
3204 strcpy(config
->random_device
, RANDOMDEVICE
);
3206 log_stream
= stderr
;
3209 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
3211 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
3214 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
3217 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
3219 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
3222 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
3224 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
3227 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
3229 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
3233 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
3235 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
3239 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
3241 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
3245 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
3247 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
3251 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
3253 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
3256 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
3258 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
3260 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
3263 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
3265 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
3267 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
3270 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
3272 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
3273 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
3274 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
3275 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
3277 // Put all the sessions on the free list marked as undefined.
3278 for (i
= 1; i
< MAXSESSION
; i
++)
3280 session
[i
].next
= i
+ 1;
3281 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
3283 session
[MAXSESSION
- 1].next
= 0;
3286 // Mark all the tunnels as undefined (waiting to be filled in by a download).
3287 for (i
= 1; i
< MAXTUNNEL
; i
++)
3288 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
3292 // Grab my hostname unless it's been specified
3293 gethostname(hostname
, sizeof(hostname
));
3294 stripdomain(hostname
);
3297 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
3300 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
3302 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
3308 static int assign_ip_address(sessionidt s
)
3312 time_t best_time
= time_now
;
3313 char *u
= session
[s
].user
;
3317 CSTAT(assign_ip_address
);
3319 for (i
= 1; i
< ip_pool_size
; i
++)
3321 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
3324 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
3331 if (ip_address_pool
[i
].last
< best_time
)
3334 if (!(best_time
= ip_address_pool
[i
].last
))
3335 break; // never used, grab this one
3341 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
3345 session
[s
].ip
= ip_address_pool
[best
].address
;
3346 session
[s
].ip_pool_index
= best
;
3347 ip_address_pool
[best
].assigned
= 1;
3348 ip_address_pool
[best
].last
= time_now
;
3349 ip_address_pool
[best
].session
= s
;
3350 if (session
[s
].walled_garden
)
3351 /* Don't track addresses of users in walled garden (note: this
3352 means that their address isn't "sticky" even if they get
3354 ip_address_pool
[best
].user
[0] = 0;
3356 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
3359 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
3360 reuse
? "Reusing" : "Allocating", best
);
3365 static void free_ip_address(sessionidt s
)
3367 int i
= session
[s
].ip_pool_index
;
3370 CSTAT(free_ip_address
);
3373 return; // what the?
3375 if (i
< 0) // Is this actually part of the ip pool?
3379 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
3381 ip_address_pool
[i
].assigned
= 0;
3382 ip_address_pool
[i
].session
= 0;
3383 ip_address_pool
[i
].last
= time_now
;
3387 // Fsck the address pool against the session table.
3388 // Normally only called when we become a master.
3390 // This isn't perfect: We aren't keep tracking of which
3391 // users used to have an IP address.
3393 void rebuild_address_pool(void)
3398 // Zero the IP pool allocation, and build
3399 // a map from IP address to pool index.
3400 for (i
= 1; i
< MAXIPPOOL
; ++i
)
3402 ip_address_pool
[i
].assigned
= 0;
3403 ip_address_pool
[i
].session
= 0;
3404 if (!ip_address_pool
[i
].address
)
3407 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
3410 for (i
= 0; i
< MAXSESSION
; ++i
)
3413 if (!(session
[i
].opened
&& session
[i
].ip
))
3416 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
3418 if (session
[i
].ip_pool_index
< 0)
3420 // Not allocated out of the pool.
3421 if (ipid
< 1) // Not found in the pool either? good.
3424 LOG(0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
3425 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
3427 // Fall through and process it as part of the pool.
3431 if (ipid
> MAXIPPOOL
|| ipid
< 0)
3433 LOG(0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
3435 session
[i
].ip_pool_index
= ipid
;
3439 ip_address_pool
[ipid
].assigned
= 1;
3440 ip_address_pool
[ipid
].session
= i
;
3441 ip_address_pool
[ipid
].last
= time_now
;
3442 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
3443 session
[i
].ip_pool_index
= ipid
;
3444 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
3449 // Fix the address pool to match a changed session.
3450 // (usually when the master sends us an update).
3451 static void fix_address_pool(int sid
)
3455 ipid
= session
[sid
].ip_pool_index
;
3457 if (ipid
> ip_pool_size
)
3458 return; // Ignore it. rebuild_address_pool will fix it up.
3460 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
3461 return; // Just ignore it. rebuild_address_pool will take care of it.
3463 ip_address_pool
[ipid
].assigned
= 1;
3464 ip_address_pool
[ipid
].session
= sid
;
3465 ip_address_pool
[ipid
].last
= time_now
;
3466 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
3470 // Add a block of addresses to the IP pool to hand out.
3472 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
3476 mask
= 0xffffffff; // Host route only.
3480 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
3483 for (i
= addr
;(i
& mask
) == addr
; ++i
)
3485 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
3486 continue; // Skip 0 and broadcast addresses.
3488 ip_address_pool
[ip_pool_size
].address
= i
;
3489 ip_address_pool
[ip_pool_size
].assigned
= 0;
3491 if (ip_pool_size
>= MAXIPPOOL
)
3493 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
3499 // Initialize the IP address pool
3500 static void initippool()
3505 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
3507 if (!(f
= fopen(IPPOOLFILE
, "r")))
3509 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
3513 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
3516 buf
[4095] = 0; // Force it to be zero terminated/
3518 if (*buf
== '#' || *buf
== '\n')
3519 continue; // Skip comments / blank lines
3520 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
3521 if ((p
= (char *)strchr(buf
, ':')))
3525 src
= inet_addr(buf
);
3526 if (src
== INADDR_NONE
)
3528 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
3531 // This entry is for a specific IP only
3532 if (src
!= config
->bind_address
)
3537 if ((p
= (char *)strchr(pool
, '/')))
3541 in_addr_t start
= 0, mask
= 0;
3543 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
3545 if (!*p
|| !(numbits
= atoi(p
)))
3547 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
3550 start
= ntohl(inet_addr(pool
));
3551 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
3553 // Add a static route for this pool
3554 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
3555 fmtaddr(htonl(start
), 0), 32 + mask
);
3557 routeset(0, start
, mask
, 0, 1);
3559 add_to_ip_pool(start
, mask
);
3563 // It's a single ip address
3564 add_to_ip_pool(inet_addr(pool
), 0);
3568 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
3571 void snoop_send_packet(char *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
3573 struct sockaddr_in snoop_addr
= {0};
3574 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
3577 snoop_addr
.sin_family
= AF_INET
;
3578 snoop_addr
.sin_addr
.s_addr
= destination
;
3579 snoop_addr
.sin_port
= ntohs(port
);
3581 LOG(5, 0, 0, "Snooping %d byte packet to %s:%d\n", size
,
3582 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
3583 htons(snoop_addr
.sin_port
));
3585 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
3586 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
3588 STAT(packets_snooped
);
3591 static int dump_session(FILE **f
, sessiont
*s
)
3593 if (!s
->opened
|| !s
->ip
|| !(s
->cin
|| s
->cout
) || !*s
->user
|| s
->walled_garden
)
3598 char filename
[1024];
3600 time_t now
= time(NULL
);
3602 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
3603 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
3605 if (!(*f
= fopen(filename
, "w")))
3607 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
3611 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
3612 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
3616 "# format: username ip qos uptxoctets downrxoctets\n",
3622 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
3623 fprintf(*f
, "%s %s %d %u %u\n",
3624 s
->user
, // username
3625 fmtaddr(htonl(s
->ip
), 0), // ip
3626 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
3627 (uint32_t) s
->cin
, // uptxoctets
3628 (uint32_t) s
->cout
); // downrxoctets
3630 s
->pin
= s
->cin
= 0;
3631 s
->pout
= s
->cout
= 0;
3636 static void dump_acct_info(int all
)
3642 CSTAT(dump_acct_info
);
3646 for (i
= 0; i
< shut_acct_n
; i
++)
3647 dump_session(&f
, &shut_acct
[i
]);
3653 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3654 dump_session(&f
, &session
[i
]);
3661 int main(int argc
, char *argv
[])
3665 char *optconfig
= CONFIGFILE
;
3667 time(&basetime
); // start clock
3670 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
3675 if (fork()) exit(0);
3677 freopen("/dev/null", "r", stdin
);
3678 freopen("/dev/null", "w", stdout
);
3679 freopen("/dev/null", "w", stderr
);
3688 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
3691 printf("Args are:\n"
3692 "\t-d\t\tDetach from terminal\n"
3693 "\t-c <file>\tConfig file\n"
3694 "\t-h <hostname>\tForce hostname\n"
3702 // Start the timer routine off
3704 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3705 signal(SIGALRM
, sigalrm_handler
);
3706 siginterrupt(SIGALRM
, 0);
3709 initdata(optdebug
, optconfig
);
3713 init_tbf(config
->num_tbfs
);
3715 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
3716 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005 Optus Internet Engineering\n");
3717 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3720 rlim
.rlim_cur
= RLIM_INFINITY
;
3721 rlim
.rlim_max
= RLIM_INFINITY
;
3722 // Remove the maximum core size
3723 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
3724 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
3726 // Make core dumps go to /tmp
3730 if (config
->scheduler_fifo
)
3733 struct sched_param params
= {0};
3734 params
.sched_priority
= 1;
3736 if (get_nprocs() < 2)
3738 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3739 config
->scheduler_fifo
= 0;
3743 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3745 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3749 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3750 config
->scheduler_fifo
= 0;
3755 /* Set up the cluster communications port. */
3756 if (cluster_init() < 0)
3760 signal(SIGPIPE
, SIG_IGN
);
3761 bgp_setup(config
->as_number
);
3762 bgp_add_route(config
->bind_address
, 0xffffffff);
3763 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3765 if (config
->neighbour
[i
].name
[0])
3766 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3767 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3768 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3773 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3779 signal(SIGHUP
, sighup_handler
);
3780 signal(SIGTERM
, sigterm_handler
);
3781 signal(SIGINT
, sigterm_handler
);
3782 signal(SIGQUIT
, sigquit_handler
);
3783 signal(SIGCHLD
, sigchild_handler
);
3785 // Prevent us from getting paged out
3786 if (config
->lock_pages
)
3788 if (!mlockall(MCL_CURRENT
))
3789 LOG(1, 0, 0, "Locking pages into memory\n");
3791 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3796 // Drop privileges here
3797 if (config
->target_uid
> 0 && geteuid() == 0)
3798 setuid(config
->target_uid
);
3803 /* try to shut BGP down cleanly; with luck the sockets will be
3804 writable since we're out of the select */
3805 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3806 if (bgp_peers
[i
].state
== Established
)
3807 bgp_stop(&bgp_peers
[i
]);
3810 /* remove plugins (so cleanup code gets run) */
3813 // Remove the PID file if we wrote it
3814 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3815 unlink(config
->pid_file
);
3817 /* kill CLI children */
3818 signal(SIGTERM
, SIG_IGN
);
3823 static void sighup_handler(int sig
)
3827 if (log_stream
!= stderr
)
3836 static void sigalrm_handler(int sig
)
3838 // Log current traffic stats
3840 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3841 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3842 (udp_rx
/ 1024.0 / 1024.0 * 8),
3843 (eth_tx
/ 1024.0 / 1024.0 * 8),
3844 (eth_rx
/ 1024.0 / 1024.0 * 8),
3845 (udp_tx
/ 1024.0 / 1024.0 * 8),
3846 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3847 udp_rx_pkt
, eth_rx_pkt
);
3849 udp_tx
= udp_rx
= 0;
3850 udp_rx_pkt
= eth_rx_pkt
= 0;
3851 eth_tx
= eth_rx
= 0;
3853 if (config
->dump_speed
)
3854 printf("%s\n", config
->bandwidth
);
3856 // Update the internal time counter
3858 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3863 struct param_timer p
= { time_now
};
3864 run_plugins(PLUGIN_TIMER
, &p
);
3869 static void sigterm_handler(int sig
)
3871 LOG(1, 0, 0, "Shutting down cleanly\n");
3875 static void sigquit_handler(int sig
)
3879 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3881 if (config
->cluster_iam_master
)
3883 for (i
= 1; i
< MAXSESSION
; i
++)
3885 if (session
[i
].opened
)
3886 sessionkill(i
, "L2TPNS Closing");
3888 for (i
= 1; i
< MAXTUNNEL
; i
++)
3890 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3891 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3898 static void sigchild_handler(int sig
)
3900 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3904 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
)
3907 *challenge_response
= NULL
;
3909 if (!*config
->l2tpsecret
)
3911 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3915 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
3917 *challenge_response
= (char *)calloc(17, 1);
3920 MD5Update(&ctx
, &id
, 1);
3921 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3922 MD5Update(&ctx
, challenge
, challenge_length
);
3923 MD5Final(*challenge_response
, &ctx
);
3928 static int facility_value(char *name
)
3931 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3933 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3934 return facilitynames
[i
].c_val
;
3939 static void update_config()
3943 static int timeout
= 0;
3944 static int interval
= 0;
3951 if (log_stream
!= stderr
)
3957 if (*config
->log_filename
)
3959 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3961 char *p
= config
->log_filename
+ 7;
3964 openlog("l2tpns", LOG_PID
, facility_value(p
));
3968 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3970 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3972 fseek(log_stream
, 0, SEEK_END
);
3973 setbuf(log_stream
, NULL
);
3977 log_stream
= stderr
;
3978 setbuf(log_stream
, NULL
);
3984 log_stream
= stderr
;
3985 setbuf(log_stream
, NULL
);
3989 config
->numradiusservers
= 0;
3990 for (i
= 0; i
< MAXRADSERVER
; i
++)
3991 if (config
->radiusserver
[i
])
3993 config
->numradiusservers
++;
3994 // Set radius port: if not set, take the port from the
3995 // first radius server. For the first radius server,
3996 // take the #defined default value from l2tpns.h
3998 // test twice, In case someone works with
3999 // a secondary radius server without defining
4000 // a primary one, this will work even then.
4001 if (i
> 0 && !config
->radiusport
[i
])
4002 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4003 if (!config
->radiusport
[i
])
4004 config
->radiusport
[i
] = RADPORT
;
4007 if (!config
->numradiusservers
)
4008 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4010 config
->num_radfds
= 1 << RADIUS_SHIFT
;
4012 // parse radius_authtypes_s
4013 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4014 p
= config
->radius_authtypes_s
;
4017 char *s
= strpbrk(p
, " \t,");
4023 while (*s
== ' ' || *s
== '\t')
4030 if (!strncasecmp("chap", p
, strlen(p
)))
4032 else if (!strncasecmp("pap", p
, strlen(p
)))
4035 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4037 config
->radius_authtypes
|= type
;
4038 if (!config
->radius_authprefer
)
4039 config
->radius_authprefer
= type
;
4044 if (!config
->radius_authtypes
)
4046 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4047 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4050 // normalise radius_authtypes_s
4051 if (config
->radius_authprefer
== AUTHPAP
)
4053 strcpy(config
->radius_authtypes_s
, "pap");
4054 if (config
->radius_authtypes
& AUTHCHAP
)
4055 strcat(config
->radius_authtypes_s
, ", chap");
4059 strcpy(config
->radius_authtypes_s
, "chap");
4060 if (config
->radius_authtypes
& AUTHPAP
)
4061 strcat(config
->radius_authtypes_s
, ", pap");
4064 // re-initialise the random number source
4065 initrandom(config
->random_device
);
4068 for (i
= 0; i
< MAXPLUGINS
; i
++)
4070 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
4073 if (*config
->plugins
[i
])
4076 add_plugin(config
->plugins
[i
]);
4078 else if (*config
->old_plugins
[i
])
4081 remove_plugin(config
->old_plugins
[i
]);
4085 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
4086 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
4087 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
4088 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
4089 if (!*config
->cluster_interface
)
4090 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
4092 if (!config
->cluster_hb_interval
)
4093 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
4095 if (!config
->cluster_hb_timeout
)
4096 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
4098 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
4100 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
4101 // late, ensure we're sufficiently larger than that
4102 int t
= 4 * config
->cluster_hb_interval
+ 11;
4104 if (config
->cluster_hb_timeout
< t
)
4106 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
4107 config
->cluster_hb_timeout
= t
;
4110 // Push timing changes to the slaves immediately if we're the master
4111 if (config
->cluster_iam_master
)
4112 cluster_heartbeat();
4114 interval
= config
->cluster_hb_interval
;
4115 timeout
= config
->cluster_hb_timeout
;
4119 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
4122 if ((f
= fopen(config
->pid_file
, "w")))
4124 fprintf(f
, "%d\n", getpid());
4126 config
->wrote_pid
= 1;
4130 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
4134 config
->reload_config
= 0;
4137 static void read_config_file()
4141 if (!config
->config_file
) return;
4142 if (!(f
= fopen(config
->config_file
, "r")))
4144 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
4148 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
4150 LOG(3, 0, 0, "Done reading config file\n");
4155 int sessionsetup(tunnelidt t
, sessionidt s
)
4157 // A session now exists, set it up
4163 CSTAT(sessionsetup
);
4165 LOG(3, s
, t
, "Doing session setup for session\n");
4169 assign_ip_address(s
);
4172 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
4173 sessionshutdown(s
, "No IP addresses available.", 2, 7);
4176 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
4177 fmtaddr(htonl(session
[s
].ip
), 0));
4181 // Make sure this is right
4182 session
[s
].tunnel
= t
;
4184 // zap old sessions with same IP and/or username
4185 // Don't kill gardened sessions - doing so leads to a DoS
4186 // from someone who doesn't need to know the password
4189 user
= session
[s
].user
;
4190 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4192 if (i
== s
) continue;
4193 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
4194 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
4195 sessionkill(i
, "Duplicate session for users");
4202 // Add the route for this session.
4203 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
4205 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
4206 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
4209 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
4212 // Static IPs need to be routed if not already
4213 // convered by a Framed-Route. Anything else is part
4214 // of the IP address pool and is already routed, it
4215 // just needs to be added to the IP cache.
4216 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
4217 if (session
[s
].ip_pool_index
== -1) // static ip
4219 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
4222 cache_ipmap(session
[s
].ip
, s
);
4225 if (!session
[s
].unique_id
)
4227 // did this session just finish radius?
4228 LOG(3, s
, t
, "Sending initial IPCP to client\n");
4230 session
[s
].unique_id
= ++last_id
;
4233 // Run the plugin's against this new session.
4235 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
4236 run_plugins(PLUGIN_NEW_SESSION
, &data
);
4239 // Allocate TBFs if throttled
4240 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
4241 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
4243 session
[s
].last_packet
= time_now
;
4245 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
4246 fmtaddr(htonl(session
[s
].ip
), 0),
4247 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
4249 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
4251 return 1; // RADIUS OK and IP allocated, done...
4255 // This session just got dropped on us by the master or something.
4256 // Make sure our tables up up to date...
4258 int load_session(sessionidt s
, sessiont
*new)
4264 if (new->ip_pool_index
>= MAXIPPOOL
||
4265 new->tunnel
>= MAXTUNNEL
)
4267 LOG(0, s
, 0, "Strange session update received!\n");
4268 // FIXME! What to do here?
4273 // Ok. All sanity checks passed. Now we're committed to
4274 // loading the new session.
4277 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
4279 // See if routes/ip cache need updating
4280 if (new->ip
!= session
[s
].ip
)
4283 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
4284 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
4285 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
4293 // remove old routes...
4294 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
4296 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
4297 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
4300 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
4306 if (session
[s
].ip_pool_index
== -1) // static IP
4308 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
4310 else // It's part of the IP pool, remove it manually.
4311 uncache_ipmap(session
[s
].ip
);
4316 // add new routes...
4317 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
4319 if ((new->ip
& new->route
[i
].mask
) ==
4320 (new->route
[i
].ip
& new->route
[i
].mask
))
4323 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
4329 // If there's a new one, add it.
4330 if (new->ip_pool_index
== -1)
4332 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
4335 cache_ipmap(new->ip
, s
);
4340 if (new->flags
& SF_IPV6_ROUTED
&& !(session
[s
].flags
& SF_IPV6_ROUTED
))
4341 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
4344 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
4346 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %d\n", (int) new->filter_in
);
4350 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
4352 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %d\n", (int) new->filter_out
);
4353 new->filter_out
= 0;
4356 if (new->filter_in
!= session
[s
].filter_in
)
4358 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
4359 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
4362 if (new->filter_out
!= session
[s
].filter_out
)
4364 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
4365 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
4368 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
4369 // for walking the sessions to forward byte counts to the master.
4370 config
->cluster_highest_sessionid
= s
;
4372 // TEMP: old session struct used a uint32_t to define the throttle
4373 // speed for both up/down, new uses a uint16_t for each. Deal with
4374 // sessions from an old master for migration.
4375 if (new->throttle_out
== 0 && new->tbf_out
)
4376 new->throttle_out
= new->throttle_in
;
4378 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
4380 // Do fixups into address pool.
4381 if (new->ip_pool_index
!= -1)
4382 fix_address_pool(s
);
4387 static void initplugins()
4391 loaded_plugins
= ll_init();
4392 // Initialize the plugins to nothing
4393 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
4394 plugins
[i
] = ll_init();
4397 static void *open_plugin(char *plugin_name
, int load
)
4399 char path
[256] = "";
4401 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
4402 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
4403 return dlopen(path
, RTLD_NOW
);
4406 // plugin callback to get a config value
4407 static void *getconfig(char *key
, enum config_typet type
)
4411 for (i
= 0; config_values
[i
].key
; i
++)
4413 if (!strcmp(config_values
[i
].key
, key
))
4415 if (config_values
[i
].type
== type
)
4416 return ((void *) config
) + config_values
[i
].offset
;
4418 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
4419 key
, type
, config_values
[i
].type
);
4425 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
4429 static int add_plugin(char *plugin_name
)
4431 static struct pluginfuncs funcs
= {
4436 sessiontbysessionidt
,
4437 sessionidtbysessiont
,
4444 cluster_send_session
,
4447 void *p
= open_plugin(plugin_name
, 1);
4448 int (*initfunc
)(struct pluginfuncs
*);
4453 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
4457 if (ll_contains(loaded_plugins
, p
))
4460 return 0; // already loaded
4464 int *v
= dlsym(p
, "plugin_api_version");
4465 if (!v
|| *v
!= PLUGIN_API_VERSION
)
4467 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
4473 if ((initfunc
= dlsym(p
, "plugin_init")))
4475 if (!initfunc(&funcs
))
4477 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
4483 ll_push(loaded_plugins
, p
);
4485 for (i
= 0; i
< max_plugin_functions
; i
++)
4488 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4490 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
4491 ll_push(plugins
[i
], x
);
4495 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
4499 static void run_plugin_done(void *plugin
)
4501 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
4507 static int remove_plugin(char *plugin_name
)
4509 void *p
= open_plugin(plugin_name
, 0);
4515 if (ll_contains(loaded_plugins
, p
))
4518 for (i
= 0; i
< max_plugin_functions
; i
++)
4521 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4522 ll_delete(plugins
[i
], x
);
4525 ll_delete(loaded_plugins
, p
);
4531 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
4535 int run_plugins(int plugin_type
, void *data
)
4537 int (*func
)(void *data
);
4539 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
4540 return PLUGIN_RET_ERROR
;
4542 ll_reset(plugins
[plugin_type
]);
4543 while ((func
= ll_next(plugins
[plugin_type
])))
4547 if (r
!= PLUGIN_RET_OK
)
4548 return r
; // stop here
4551 return PLUGIN_RET_OK
;
4554 static void plugins_done()
4558 ll_reset(loaded_plugins
);
4559 while ((p
= ll_next(loaded_plugins
)))
4563 static void processcontrol(uint8_t * buf
, int len
, struct sockaddr_in
*addr
, int alen
)
4565 struct nsctl request
;
4566 struct nsctl response
;
4567 int type
= unpack_control(&request
, buf
, len
);
4571 if (log_stream
&& config
->debug
>= 4)
4575 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4576 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
4580 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4581 dump_control(&request
, log_stream
);
4587 case NSCTL_REQ_LOAD
:
4588 if (request
.argc
!= 1)
4590 response
.type
= NSCTL_RES_ERR
;
4592 response
.argv
[0] = "name of plugin required";
4594 else if ((r
= add_plugin(request
.argv
[0])) < 1)
4596 response
.type
= NSCTL_RES_ERR
;
4598 response
.argv
[0] = !r
4599 ? "plugin already loaded"
4600 : "error loading plugin";
4604 response
.type
= NSCTL_RES_OK
;
4610 case NSCTL_REQ_UNLOAD
:
4611 if (request
.argc
!= 1)
4613 response
.type
= NSCTL_RES_ERR
;
4615 response
.argv
[0] = "name of plugin required";
4617 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
4619 response
.type
= NSCTL_RES_ERR
;
4621 response
.argv
[0] = !r
4622 ? "plugin not loaded"
4623 : "plugin not found";
4627 response
.type
= NSCTL_RES_OK
;
4633 case NSCTL_REQ_HELP
:
4634 response
.type
= NSCTL_RES_OK
;
4637 ll_reset(loaded_plugins
);
4638 while ((p
= ll_next(loaded_plugins
)))
4640 char **help
= dlsym(p
, "plugin_control_help");
4641 while (response
.argc
< 0xff && help
&& *help
)
4642 response
.argv
[response
.argc
++] = *help
++;
4647 case NSCTL_REQ_CONTROL
:
4649 struct param_control param
= {
4650 config
->cluster_iam_master
,
4657 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4659 if (r
== PLUGIN_RET_ERROR
)
4661 response
.type
= NSCTL_RES_ERR
;
4663 response
.argv
[0] = param
.additional
4665 : "error returned by plugin";
4667 else if (r
== PLUGIN_RET_NOTMASTER
)
4669 static char msg
[] = "must be run on master: 000.000.000.000";
4671 response
.type
= NSCTL_RES_ERR
;
4673 if (config
->cluster_master_address
)
4675 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
4676 response
.argv
[0] = msg
;
4680 response
.argv
[0] = "must be run on master: none elected";
4683 else if (!(param
.response
& NSCTL_RESPONSE
))
4685 response
.type
= NSCTL_RES_ERR
;
4687 response
.argv
[0] = param
.response
4688 ? "unrecognised response value from plugin"
4689 : "unhandled action";
4693 response
.type
= param
.response
;
4695 if (param
.additional
)
4698 response
.argv
[0] = param
.additional
;
4706 response
.type
= NSCTL_RES_ERR
;
4708 response
.argv
[0] = "error unpacking control packet";
4711 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4714 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4718 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4721 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4722 if (log_stream
&& config
->debug
>= 4)
4724 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4725 dump_control(&response
, log_stream
);
4729 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4730 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
4735 static tunnelidt
new_tunnel()
4738 for (i
= 1; i
< MAXTUNNEL
; i
++)
4740 if (tunnel
[i
].state
== TUNNELFREE
)
4742 LOG(4, 0, i
, "Assigning tunnel ID %d\n", i
);
4743 if (i
> config
->cluster_highest_tunnelid
)
4744 config
->cluster_highest_tunnelid
= i
;
4748 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4753 // We're becoming the master. Do any required setup..
4755 // This is principally telling all the plugins that we're
4756 // now a master, and telling them about all the sessions
4757 // that are active too..
4759 void become_master(void)
4762 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4764 // running a bunch of iptables commands is slow and can cause
4765 // the master to drop tunnels on takeover--kludge around the
4766 // problem by forking for the moment (note: race)
4767 if (!fork_and_close())
4769 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4771 if (!session
[s
].opened
) // Not an in-use session.
4774 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4780 for (i
= 0; i
< config
->num_radfds
; i
++)
4782 FD_SET(radfds
[i
], &readset
);
4783 if (radfds
[i
] > readset_n
)
4784 readset_n
= radfds
[i
];
4788 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4794 if (CLI_HELP_REQUESTED
)
4795 return CLI_HELP_NO_ARGS
;
4798 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4800 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4803 if (!session
[s
].opened
)
4806 idle
= time_now
- session
[s
].last_packet
;
4807 idle
/= 5 ; // In multiples of 5 seconds.
4817 for (i
= 0; i
< 63; ++i
)
4819 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4821 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4822 cli_print(cli
, "%d total sessions open.", count
);
4826 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4832 if (CLI_HELP_REQUESTED
)
4833 return CLI_HELP_NO_ARGS
;
4836 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4838 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4841 if (!session
[s
].opened
)
4844 d
= time_now
- session
[s
].opened
;
4847 while (d
> 1 && open
< 32)
4857 for (i
= 0; i
< 30; ++i
)
4859 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4862 cli_print(cli
, "%d total sessions open.", count
);
4868 * This unencodes the AVP using the L2TP secret and the previously
4869 * stored random vector. It overwrites the hidden data with the
4870 * unhidden AVP subformat.
4872 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
4879 // Compute initial pad
4881 MD5Update(&ctx
, (uint8_t) (type
>> 8) & 0xff, 1);
4882 MD5Update(&ctx
, (uint8_t) type
& 0xff, 1);
4883 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4884 MD5Update(&ctx
, vector
, vec_len
);
4885 MD5Final(digest
, &ctx
);
4887 // pointer to last decoded 16 octets
4892 // calculate a new pad based on the last decoded block
4893 if (d
>= sizeof(digest
))
4896 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4897 MD5Update(&ctx
, last
, sizeof(digest
));
4898 MD5Final(digest
, &ctx
);
4904 *value
++ ^= digest
[d
++];
4909 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
4913 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
4914 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
4915 case FILTER_PORT_OP_GT
: return port
> p
->port
;
4916 case FILTER_PORT_OP_LT
: return port
< p
->port
;
4917 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
4923 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
4927 case FILTER_FLAG_OP_ANY
:
4928 return (flags
& sflags
) || (~flags
& cflags
);
4930 case FILTER_FLAG_OP_ALL
:
4931 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
4933 case FILTER_FLAG_OP_EST
:
4934 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
4940 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
4942 uint16_t frag_offset
;
4946 uint16_t src_port
= 0;
4947 uint16_t dst_port
= 0;
4949 ip_filter_rulet
*rule
;
4951 if (len
< 20) // up to end of destination address
4954 if ((*buf
>> 4) != 4) // IPv4
4957 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
4959 src_ip
= *(in_addr_t
*) (buf
+ 12);
4960 dst_ip
= *(in_addr_t
*) (buf
+ 16);
4962 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
4964 int l
= (buf
[0] & 0xf) * 4; // length of IP header
4965 if (len
< l
+ 4) // ports
4968 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
4969 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
4970 if (proto
== IPPROTO_TCP
)
4972 if (len
< l
+ 14) // flags
4975 flags
= buf
[l
+ 13] & 0x3f;
4979 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
4981 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
4984 if (rule
->src_wild
!= INADDR_BROADCAST
&&
4985 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
4988 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
4989 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
4994 if (!rule
->frag
|| rule
->action
== FILTER_ACTION_DENY
)
5002 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
5004 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
5007 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
5010 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
5011 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
5018 return rule
->action
== FILTER_ACTION_PERMIT
;