3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
7 char const *cvs_id_l2tpns
= "$Id: l2tpns.c,v 1.170 2006/07/01 14:07:35 bodea Exp $";
13 #include <linux/if_tun.h>
18 #include <net/route.h>
21 #include <netinet/in.h>
22 #include <netinet/ip6.h>
28 #include <sys/ioctl.h>
29 #include <sys/socket.h>
32 #include <sys/resource.h>
40 #include <sys/sysinfo.h>
48 #include "constants.h"
58 configt
*config
= NULL
; // all configuration
59 int tunfd
= -1; // tun interface file handle. (network device)
60 int udpfd
= -1; // UDP file handle
61 int controlfd
= -1; // Control signal handle
62 int clifd
= -1; // Socket listening for CLI connections.
63 int daefd
= -1; // Socket listening for DAE connections.
64 int snoopfd
= -1; // UDP file handle for sending out intercept data
65 int *radfds
= NULL
; // RADIUS requests file handles
66 int ifrfd
= -1; // File descriptor for routing, etc
67 int ifr6fd
= -1; // File descriptor for IPv6 routing, etc
68 int rand_fd
= -1; // Random data source
69 int cluster_sockfd
= -1; // Intra-cluster communications socket.
70 int epollfd
= -1; // event polling
71 time_t basetime
= 0; // base clock
72 char hostname
[1000] = ""; // us.
73 static int tunidx
; // ifr_ifindex of tun device
74 static int syslog_log
= 0; // are we logging to syslog
75 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
76 uint32_t last_id
= 0; // Unique ID for radius accounting
78 // calculated from config->l2tp_mtu
79 uint16_t MRU
= 0; // PPP MRU
80 uint16_t MSS
= 0; // TCP MSS
82 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
83 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
88 } ip_hash
[256]; // Mapping from IP address to session structures.
92 struct ipv6radix
*branch
;
93 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
96 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
97 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
100 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
101 time_t time_now
= 0; // Current time in seconds since epoch.
102 static char time_now_string
[64] = {0}; // Current time as a string.
103 static int time_changed
= 0; // time_now changed
104 char main_quit
= 0; // True if we're in the process of exiting.
105 static char main_reload
= 0; // Re-load pending
106 linked_list
*loaded_plugins
;
107 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
109 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
110 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
112 config_descriptt config_values
[] = {
113 CONFIG("debug", debug
, INT
),
114 CONFIG("log_file", log_filename
, STRING
),
115 CONFIG("pid_file", pid_file
, STRING
),
116 CONFIG("random_device", random_device
, STRING
),
117 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
118 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
119 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
120 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
121 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
122 CONFIG("primary_dns", default_dns1
, IPv4
),
123 CONFIG("secondary_dns", default_dns2
, IPv4
),
124 CONFIG("primary_radius", radiusserver
[0], IPv4
),
125 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
126 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
127 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
128 CONFIG("radius_accounting", radius_accounting
, BOOL
),
129 CONFIG("radius_interim", radius_interim
, INT
),
130 CONFIG("radius_secret", radiussecret
, STRING
),
131 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
132 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
133 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
134 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
135 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
136 CONFIG("guest_account", guest_user
, STRING
),
137 CONFIG("bind_address", bind_address
, IPv4
),
138 CONFIG("peer_address", peer_address
, IPv4
),
139 CONFIG("send_garp", send_garp
, BOOL
),
140 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
141 CONFIG("throttle_buckets", num_tbfs
, INT
),
142 CONFIG("accounting_dir", accounting_dir
, STRING
),
143 CONFIG("dump_speed", dump_speed
, BOOL
),
144 CONFIG("multi_read_count", multi_read_count
, INT
),
145 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
146 CONFIG("lock_pages", lock_pages
, BOOL
),
147 CONFIG("icmp_rate", icmp_rate
, INT
),
148 CONFIG("packet_limit", max_packets
, INT
),
149 CONFIG("cluster_address", cluster_address
, IPv4
),
150 CONFIG("cluster_interface", cluster_interface
, STRING
),
151 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
152 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
153 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
154 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
155 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
159 static char *plugin_functions
[] = {
166 "plugin_new_session",
167 "plugin_kill_session",
169 "plugin_radius_response",
170 "plugin_radius_reset",
171 "plugin_radius_account",
172 "plugin_become_master",
173 "plugin_new_session_master",
176 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
178 // Counters for shutdown sessions
179 static sessiont shut_acct
[8192];
180 static sessionidt shut_acct_n
= 0;
182 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
183 bundlet
*bundle
= NULL
; // Array of bundle structures.
184 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
185 sessiont
*session
= NULL
; // Array of session structures.
186 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
187 radiust
*radius
= NULL
; // Array of radius structures.
188 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
189 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
190 static controlt
*controlfree
= 0;
191 struct Tstats
*_statistics
= NULL
;
193 struct Tringbuffer
*ringbuffer
= NULL
;
196 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
197 static void uncache_ipmap(in_addr_t ip
);
198 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
199 static void free_ip_address(sessionidt s
);
200 static void dump_acct_info(int all
);
201 static void sighup_handler(int sig
);
202 static void shutdown_handler(int sig
);
203 static void sigchild_handler(int sig
);
204 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
205 static void update_config(void);
206 static void read_config_file(void);
207 static void initplugins(void);
208 static int add_plugin(char *plugin_name
);
209 static int remove_plugin(char *plugin_name
);
210 static void plugins_done(void);
211 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
212 static tunnelidt
new_tunnel(void);
213 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
214 static void bundleclear(bundleidt b
);
216 // on slaves, alow BGP to withdraw cleanly before exiting
219 // quit actions (master)
220 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
221 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
223 // return internal time (10ths since process startup), set f if given
224 // as a side-effect sets time_now, and time_changed
225 static clockt
now(double *f
)
229 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
230 if (t
.tv_sec
!= time_now
)
235 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
238 // work out a retry time based on try number
239 // This is a straight bounded exponential backoff.
240 // Maximum re-try time is 32 seconds. (2^5).
241 clockt
backoff(uint8_t try)
243 if (try > 5) try = 5; // max backoff
244 return now(NULL
) + 10 * (1 << try);
249 // Log a debug message. Typically called via the LOG macro
251 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
253 static char message
[65536] = {0};
259 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
260 ringbuffer
->tail
= 0;
261 if (ringbuffer
->tail
== ringbuffer
->head
)
262 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
263 ringbuffer
->head
= 0;
265 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
266 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
267 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
268 va_start(ap
, format
);
269 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
274 if (config
->debug
< level
) return;
276 va_start(ap
, format
);
277 vsnprintf(message
, sizeof(message
), format
, ap
);
280 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
282 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
287 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
290 const uint8_t *d
= data
;
292 if (config
->debug
< level
) return;
294 // No support for _log_hex to syslog
297 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
298 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
300 for (i
= 0; i
< maxsize
; )
302 fprintf(log_stream
, "%4X: ", i
);
303 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
305 fprintf(log_stream
, "%02X ", d
[j
]);
307 fputs(": ", log_stream
);
310 for (; j
< i
+ 16; j
++)
312 fputs(" ", log_stream
);
314 fputs(": ", log_stream
);
317 fputs(" ", log_stream
);
318 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
320 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
321 fputc(d
[j
], log_stream
);
323 fputc('.', log_stream
);
326 fputs(" ", log_stream
);
330 fputs("\n", log_stream
);
334 setbuf(log_stream
, NULL
);
338 // update a counter, accumulating 2^32 wraps
339 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
341 uint32_t new = *counter
+ delta
;
348 // initialise the random generator
349 static void initrandom(char *source
)
351 static char path
[sizeof(config
->random_device
)] = "*undefined*";
353 // reinitialise only if we are forced to do so or if the config has changed
354 if (source
&& !strncmp(path
, source
, sizeof(path
)))
357 // close previous source, if any
366 snprintf(path
, sizeof(path
), "%s", source
);
370 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
372 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
373 path
, strerror(errno
));
378 // fill buffer with random data
379 void random_data(uint8_t *buf
, int len
)
386 n
= read(rand_fd
, buf
, len
);
387 if (n
>= len
) return;
392 LOG(0, 0, 0, "Error reading from random source: %s\n",
395 // fall back to rand()
403 // append missing data
405 // not using the low order bits from the prng stream
406 buf
[n
++] = (rand() >> 4) & 0xff;
411 // This adds it to the routing table, advertises it
412 // via BGP if enabled, and stuffs it into the
413 // 'sessionbyip' cache.
415 // 'ip' and 'mask' must be in _host_ order.
417 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
422 if (!mask
) mask
= 0xffffffff;
424 ip
&= mask
; // Force the ip to be the first one in the route.
426 memset(&r
, 0, sizeof(r
));
427 r
.rt_dev
= config
->tundevice
;
428 r
.rt_dst
.sa_family
= AF_INET
;
429 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
430 r
.rt_gateway
.sa_family
= AF_INET
;
431 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
432 r
.rt_genmask
.sa_family
= AF_INET
;
433 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
434 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
436 r
.rt_flags
|= RTF_GATEWAY
;
437 else if (mask
== 0xffffffff)
438 r
.rt_flags
|= RTF_HOST
;
440 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
441 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
442 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
444 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
445 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
449 bgp_add_route(htonl(ip
), htonl(mask
));
451 bgp_del_route(htonl(ip
), htonl(mask
));
454 // Add/Remove the IPs to the 'sessionbyip' cache.
455 // Note that we add the zero address in the case of
456 // a network route. Roll on CIDR.
458 // Note that 's == 0' implies this is the address pool.
459 // We still cache it here, because it will pre-fill
460 // the malloc'ed tree.
464 if (!add
) // Are we deleting a route?
465 s
= 0; // Caching the session as '0' is the same as uncaching.
467 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
472 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
475 char ipv6addr
[INET6_ADDRSTRLEN
];
479 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
483 memset(&rt
, 0, sizeof(rt
));
485 memcpy(&rt
.rtmsg_dst
, &ip
, sizeof(struct in6_addr
));
486 rt
.rtmsg_dst_len
= prefixlen
;
488 rt
.rtmsg_flags
= RTF_UP
;
489 rt
.rtmsg_ifindex
= tunidx
;
491 LOG(1, 0, 0, "Route %s %s/%d\n",
493 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
496 if (ioctl(ifr6fd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &rt
) < 0)
497 LOG(0, 0, 0, "route6set() error in ioctl: %s\n",
500 // FIXME: need to add BGP routing (RFC2858)
504 if (!add
) // Are we deleting a route?
505 s
= 0; // Caching the session as '0' is the same as uncaching.
507 cache_ipv6map(ip
, prefixlen
, s
);
513 // defined in linux/ipv6.h, but tricky to include from user-space
514 // TODO: move routing to use netlink rather than ioctl
516 struct in6_addr ifr6_addr
;
517 __u32 ifr6_prefixlen
;
518 unsigned int ifr6_ifindex
;
522 // Set up TUN interface
523 static void inittun(void)
526 struct in6_ifreq ifr6
;
527 struct sockaddr_in sin
= {0};
528 memset(&ifr
, 0, sizeof(ifr
));
529 ifr
.ifr_flags
= IFF_TUN
;
531 tunfd
= open(TUNDEVICE
, O_RDWR
);
534 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
538 int flags
= fcntl(tunfd
, F_GETFL
, 0);
539 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
541 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
543 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
546 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
547 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
548 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
550 sin
.sin_family
= AF_INET
;
551 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
552 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
554 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
556 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
559 /* Bump up the qlen to deal with bursts from the network */
561 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
563 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
566 /* set MTU to modem MRU */
568 if (ioctl(ifrfd
, SIOCSIFMTU
, (void *) &ifr
) < 0)
570 LOG(0, 0, 0, "Error setting tun MTU: %s\n", strerror(errno
));
573 ifr
.ifr_flags
= IFF_UP
;
574 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
576 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
579 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
581 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno
));
584 tunidx
= ifr
.ifr_ifindex
;
586 // Only setup IPv6 on the tun device if we have a configured prefix
587 if (config
->ipv6_prefix
.s6_addr
[0]) {
588 ifr6fd
= socket(PF_INET6
, SOCK_DGRAM
, 0);
590 // Link local address is FE80::1
591 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
592 ifr6
.ifr6_addr
.s6_addr
[0] = 0xFE;
593 ifr6
.ifr6_addr
.s6_addr
[1] = 0x80;
594 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
595 ifr6
.ifr6_prefixlen
= 64;
596 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
597 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
599 LOG(0, 0, 0, "Error setting tun IPv6 link local address:"
600 " %s\n", strerror(errno
));
603 // Global address is prefix::1
604 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
605 ifr6
.ifr6_addr
= config
->ipv6_prefix
;
606 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
607 ifr6
.ifr6_prefixlen
= 64;
608 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
609 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
611 LOG(0, 0, 0, "Error setting tun IPv6 global address: %s\n",
618 static void initudp(void)
621 struct sockaddr_in addr
;
624 memset(&addr
, 0, sizeof(addr
));
625 addr
.sin_family
= AF_INET
;
626 addr
.sin_port
= htons(L2TPPORT
);
627 addr
.sin_addr
.s_addr
= config
->bind_address
;
628 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
629 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
631 int flags
= fcntl(udpfd
, F_GETFL
, 0);
632 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
634 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
636 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
641 memset(&addr
, 0, sizeof(addr
));
642 addr
.sin_family
= AF_INET
;
643 addr
.sin_port
= htons(NSCTL_PORT
);
644 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
645 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
646 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
647 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
649 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
653 // Dynamic Authorization Extensions to RADIUS
654 memset(&addr
, 0, sizeof(addr
));
655 addr
.sin_family
= AF_INET
;
656 addr
.sin_port
= htons(config
->radius_dae_port
);
657 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
658 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
659 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
660 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
662 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
667 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
671 // Find session by IP, < 1 for not found
673 // Confusingly enough, this 'ip' must be
674 // in _network_ order. This being the common
675 // case when looking it up from IP packet headers.
677 // We actually use this cache for two things.
678 // #1. For used IP addresses, this maps to the
679 // session ID that it's used by.
680 // #2. For un-used IP addresses, this maps to the
681 // index into the pool table that contains that
685 static sessionidt
lookup_ipmap(in_addr_t ip
)
687 uint8_t *a
= (uint8_t *) &ip
;
688 union iphash
*h
= ip_hash
;
690 if (!(h
= h
[*a
++].idx
)) return 0;
691 if (!(h
= h
[*a
++].idx
)) return 0;
692 if (!(h
= h
[*a
++].idx
)) return 0;
697 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
699 struct ipv6radix
*curnode
;
702 char ipv6addr
[INET6_ADDRSTRLEN
];
704 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
708 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
710 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
715 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
716 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
723 sessionidt
sessionbyip(in_addr_t ip
)
725 sessionidt s
= lookup_ipmap(ip
);
728 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
734 sessionidt
sessionbyipv6(struct in6_addr ip
)
737 CSTAT(sessionbyipv6
);
739 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
740 (ip
.s6_addr
[0] == 0xFE &&
741 ip
.s6_addr
[1] == 0x80 &&
742 ip
.s6_addr16
[1] == 0 &&
743 ip
.s6_addr16
[2] == 0 &&
744 ip
.s6_addr16
[3] == 0)) {
745 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
747 s
= lookup_ipv6map(ip
);
750 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
757 // Take an IP address in HOST byte order and
758 // add it to the sessionid by IP cache.
760 // (It's actually cached in network order)
762 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
764 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
765 uint8_t *a
= (uint8_t *) &nip
;
766 union iphash
*h
= ip_hash
;
769 for (i
= 0; i
< 3; i
++)
771 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
780 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
783 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
784 // else a map to an ip pool index.
787 static void uncache_ipmap(in_addr_t ip
)
789 cache_ipmap(ip
, 0); // Assign it to the NULL session.
792 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
796 struct ipv6radix
*curnode
;
797 char ipv6addr
[INET6_ADDRSTRLEN
];
799 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
801 bytes
= prefixlen
>> 3;
804 if (curnode
->branch
== NULL
)
806 if (!(curnode
->branch
= calloc(256,
807 sizeof (struct ipv6radix
))))
810 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
817 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
818 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
822 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
823 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
829 // CLI list to dump current ipcache.
831 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
833 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
837 if (CLI_HELP_REQUESTED
)
838 return CLI_HELP_NO_ARGS
;
840 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
842 for (i
= 0; i
< 256; ++i
)
848 for (j
= 0; j
< 256; ++j
)
854 for (k
= 0; k
< 256; ++k
)
860 for (l
= 0; l
< 256; ++l
)
865 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
871 cli_print(cli
, "%d entries in cache", count
);
876 // Find session by username, 0 for not found
877 // walled garden users aren't authenticated, so the username is
878 // reasonably useless. Ignore them to avoid incorrect actions
880 // This is VERY inefficent. Don't call it often. :)
882 sessionidt
sessionbyuser(char *username
)
885 CSTAT(sessionbyuser
);
887 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
889 if (!session
[s
].opened
)
892 if (session
[s
].walled_garden
)
893 continue; // Skip walled garden users.
895 if (!strncmp(session
[s
].user
, username
, 128))
899 return 0; // Not found.
902 void send_garp(in_addr_t ip
)
908 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
911 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
914 memset(&ifr
, 0, sizeof(ifr
));
915 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
916 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
918 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
922 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
923 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
925 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
930 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
933 static sessiont
*sessiontbysessionidt(sessionidt s
)
935 if (!s
|| s
>= MAXSESSION
) return NULL
;
939 static sessionidt
sessionidtbysessiont(sessiont
*s
)
941 sessionidt val
= s
-session
;
942 if (s
< session
|| val
>= MAXSESSION
) return 0;
946 // actually send a control message for a specific tunnel
947 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
949 struct sockaddr_in addr
;
955 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
956 STAT(tunnel_tx_errors
);
962 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
963 STAT(tunnel_tx_errors
);
967 memset(&addr
, 0, sizeof(addr
));
968 addr
.sin_family
= AF_INET
;
969 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
970 addr
.sin_port
= htons(tunnel
[t
].port
);
972 // sequence expected, if sequence in message
973 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
975 // If this is a control message, deal with retries
978 tunnel
[t
].last
= time_now
; // control message sent
979 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
982 STAT(tunnel_retries
);
983 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
987 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
989 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
990 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
991 STAT(tunnel_tx_errors
);
995 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
996 STAT(tunnel_tx_packets
);
997 INC_STAT(tunnel_tx_bytes
, l
);
1001 // Tiny helper function to write data to
1002 // the 'tun' device.
1004 int tun_write(uint8_t * data
, int size
)
1006 return write(tunfd
, data
, size
);
1009 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1010 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1012 int d
= (tcp
[12] >> 4) * 4;
1019 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1022 if (tcp
+ d
> buf
+ len
) // short?
1030 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1033 if (mss
+ 2 > data
) return; // short?
1037 if (*opts
== 0) return; // end of options
1038 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1041 opts
+= opts
[1]; // skip over option
1044 if (!mss
) return; // not found
1045 orig
= ntohs(*(uint16_t *) mss
);
1047 if (orig
<= MSS
) return; // mss OK
1049 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1050 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1051 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1052 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1055 *(int16_t *) mss
= htons(MSS
);
1057 // adjust checksum (see rfc1141)
1058 sum
= orig
+ (~MSS
& 0xffff);
1059 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1060 sum
= (sum
& 0xffff) + (sum
>> 16);
1061 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1064 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1068 // Skip the four extra bytes
1073 // Process this frame
1081 proto
= ntohs(*(uint16_t *) p
);
1090 LOG(4, s
, t
, "MPPP: Session %u is closing. Don't process PPP packets\n", s
);
1091 return; // closing session, PPP not processed
1094 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1095 processipin(s
, t
, p
, l
);
1097 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1101 LOG(4, s
, t
, "MPPP: Session %u is closing. Don't process PPP packets\n", s
);
1102 return; // closing session, PPP not processed
1105 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1106 processipv6in(s
, t
, p
, l
);
1110 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1114 // process outgoing (to tunnel) IP
1116 static void processipout(uint8_t *buf
, int len
)
1123 uint8_t *data
= buf
; // Keep a copy of the originals.
1126 uint8_t b1
[MAXETHER
+ 20];
1127 uint8_t b2
[MAXETHER
+ 20];
1129 CSTAT(processipout
);
1131 if (len
< MIN_IP_SIZE
)
1133 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1134 STAT(tun_rx_errors
);
1137 if (len
>= MAXETHER
)
1139 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1140 STAT(tun_rx_errors
);
1144 // Skip the tun header
1148 // Got an IP header now
1149 if (*(uint8_t *)(buf
) >> 4 != 4)
1151 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1155 ip
= *(uint32_t *)(buf
+ 16);
1156 if (!(s
= sessionbyip(ip
)))
1158 // Is this a packet for a session that doesn't exist?
1159 static int rate
= 0; // Number of ICMP packets we've sent this second.
1160 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1162 if (last
!= time_now
)
1168 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1170 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1171 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1172 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1176 t
= session
[s
].tunnel
;
1178 sp
->last_data
= time_now
;
1180 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1181 if (config
->max_packets
> 0)
1183 if (sess_local
[s
].last_packet_out
== TIME
)
1185 int max
= config
->max_packets
;
1187 // All packets for throttled sessions are handled by the
1188 // master, so further limit by using the throttle rate.
1189 // A bit of a kludge, since throttle rate is in kbps,
1190 // but should still be generous given our average DSL
1191 // packet size is 200 bytes: a limit of 28kbps equates
1192 // to around 180 packets per second.
1193 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1194 max
= sp
->throttle_out
;
1196 if (++sess_local
[s
].packets_out
> max
)
1198 sess_local
[s
].packets_dropped
++;
1204 if (sess_local
[s
].packets_dropped
)
1206 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1207 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1208 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1209 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1213 sess_local
[s
].last_packet_out
= TIME
;
1214 sess_local
[s
].packets_out
= 1;
1215 sess_local
[s
].packets_dropped
= 0;
1219 // run access-list if any
1220 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1223 // adjust MSS on SYN and SYN,ACK packets with options
1224 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1226 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1227 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1228 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1233 // Are we throttling this session?
1234 if (config
->cluster_iam_master
)
1235 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1237 master_throttle_packet(sp
->tbf_out
, data
, size
);
1241 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1243 // We are walled-gardening this
1244 master_garden_packet(s
, data
, size
);
1248 // Add on L2TP header
1251 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1253 bid
= session
[s
].bundle
;
1254 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1255 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %u\n", s
);
1258 // Partition the packet to 2 fragments
1259 uint32_t frag1len
= len
/ 2;
1260 uint32_t frag2len
= len
- frag1len
;
1261 uint8_t *p
= makeppp(b1
, sizeof(b1
), buf
, frag1len
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1265 tunnelsend(b1
, frag1len
+ (p
-b1
), t
); // send it...
1266 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1267 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %u\n", s
);
1268 q
= makeppp(b2
, sizeof(b2
), buf
+frag1len
, frag2len
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1270 tunnelsend(b2
, frag2len
+ (q
-b2
), t
); // send it...
1273 // Send it as one frame
1274 uint8_t *p
= makeppp(b1
, sizeof(b1
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1276 tunnelsend(b1
, len
+ (p
-b1
), t
); // send it...
1281 uint8_t *p
= makeppp(b1
, sizeof(b1
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1283 tunnelsend(b1
, len
+ (p
-b1
), t
); // send it...
1287 // Snooping this session, send it to intercept box
1288 if (sp
->snoop_ip
&& sp
->snoop_port
)
1289 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1291 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1292 sp
->cout_delta
+= len
;
1296 sess_local
[s
].cout
+= len
; // To send to master..
1297 sess_local
[s
].pout
++;
1300 // process outgoing (to tunnel) IPv6
1302 static void processipv6out(uint8_t * buf
, int len
)
1308 struct in6_addr ip6
;
1310 uint8_t *data
= buf
; // Keep a copy of the originals.
1313 uint8_t b
[MAXETHER
+ 20];
1315 CSTAT(processipv6out
);
1317 if (len
< MIN_IP_SIZE
)
1319 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1320 STAT(tunnel_tx_errors
);
1323 if (len
>= MAXETHER
)
1325 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1326 STAT(tunnel_tx_errors
);
1330 // Skip the tun header
1334 // Got an IP header now
1335 if (*(uint8_t *)(buf
) >> 4 != 6)
1337 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1341 ip6
= *(struct in6_addr
*)(buf
+24);
1342 s
= sessionbyipv6(ip6
);
1346 ip
= *(uint32_t *)(buf
+ 32);
1347 s
= sessionbyip(ip
);
1352 // Is this a packet for a session that doesn't exist?
1353 static int rate
= 0; // Number of ICMP packets we've sent this second.
1354 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1356 if (last
!= time_now
)
1362 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1364 // FIXME: Should send icmp6 host unreachable
1368 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1370 bundleidt bid
= session
[s
].bundle
;
1371 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1372 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1374 t
= session
[s
].tunnel
;
1376 sp
->last_data
= time_now
;
1378 // FIXME: add DoS prevention/filters?
1382 // Are we throttling this session?
1383 if (config
->cluster_iam_master
)
1384 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1386 master_throttle_packet(sp
->tbf_out
, data
, size
);
1389 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1391 // We are walled-gardening this
1392 master_garden_packet(s
, data
, size
);
1396 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1398 // Add on L2TP header
1400 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1402 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1405 // Snooping this session, send it to intercept box
1406 if (sp
->snoop_ip
&& sp
->snoop_port
)
1407 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1409 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1410 sp
->cout_delta
+= len
;
1414 sess_local
[s
].cout
+= len
; // To send to master..
1415 sess_local
[s
].pout
++;
1419 // Helper routine for the TBF filters.
1420 // Used to send queued data in to the user!
1422 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1428 uint8_t b
[MAXETHER
+ 20];
1430 if (len
< 0 || len
> MAXETHER
)
1432 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1436 // Skip the tun header
1440 ip
= *(in_addr_t
*)(buf
+ 16);
1445 t
= session
[s
].tunnel
;
1448 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1450 // Add on L2TP header
1452 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1454 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1457 // Snooping this session.
1458 if (sp
->snoop_ip
&& sp
->snoop_port
)
1459 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1461 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1462 sp
->cout_delta
+= len
;
1466 sess_local
[s
].cout
+= len
; // To send to master..
1467 sess_local
[s
].pout
++;
1470 // add an AVP (16 bit)
1471 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1473 uint16_t l
= (m
? 0x8008 : 0x0008);
1474 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1475 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1476 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1477 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1481 // add an AVP (32 bit)
1482 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1484 uint16_t l
= (m
? 0x800A : 0x000A);
1485 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1486 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1487 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1488 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1492 // add an AVP (string)
1493 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1495 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1496 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1497 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1498 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1499 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1500 c
->length
+= 6 + strlen(val
);
1504 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1506 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1507 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1508 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1509 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1510 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1511 c
->length
+= 6 + len
;
1514 // new control connection
1515 static controlt
*controlnew(uint16_t mtype
)
1519 c
= malloc(sizeof(controlt
));
1523 controlfree
= c
->next
;
1527 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1529 control16(c
, 0, mtype
, 1);
1533 // send zero block if nothing is waiting
1535 static void controlnull(tunnelidt t
)
1538 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1541 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1542 *(uint16_t *) (buf
+ 2) = htons(12); // length
1543 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1544 *(uint16_t *) (buf
+ 6) = htons(0); // session
1545 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1546 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1547 tunnelsend(buf
, 12, t
);
1550 // add a control message to a tunnel, and send if within window
1551 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1553 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1554 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1555 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1556 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1557 tunnel
[t
].ns
++; // advance sequence
1558 // link in message in to queue
1559 if (tunnel
[t
].controlc
)
1560 tunnel
[t
].controle
->next
= c
;
1562 tunnel
[t
].controls
= c
;
1564 tunnel
[t
].controle
= c
;
1565 tunnel
[t
].controlc
++;
1567 // send now if space in window
1568 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1570 tunnel
[t
].try = 0; // first send
1571 tunnelsend(c
->buf
, c
->length
, t
);
1576 // Throttle or Unthrottle a session
1578 // Throttle the data from/to through a session to no more than
1579 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1582 // If either value is -1, the current value is retained for that
1585 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1587 if (!session
[s
].opened
)
1588 return; // No-one home.
1590 if (!*session
[s
].user
)
1591 return; // User not logged in
1595 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1596 if (session
[s
].tbf_in
)
1597 free_tbf(session
[s
].tbf_in
);
1600 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1602 session
[s
].tbf_in
= 0;
1604 session
[s
].throttle_in
= rate_in
;
1609 int bytes
= rate_out
* 1024 / 8;
1610 if (session
[s
].tbf_out
)
1611 free_tbf(session
[s
].tbf_out
);
1614 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1616 session
[s
].tbf_out
= 0;
1618 session
[s
].throttle_out
= rate_out
;
1622 // add/remove filters from session (-1 = no change)
1623 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1625 if (!session
[s
].opened
)
1626 return; // No-one home.
1628 if (!*session
[s
].user
)
1629 return; // User not logged in
1632 if (filter_in
> MAXFILTER
) filter_in
= -1;
1633 if (filter_out
> MAXFILTER
) filter_out
= -1;
1634 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1635 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1639 if (session
[s
].filter_in
)
1640 ip_filters
[session
[s
].filter_in
- 1].used
--;
1643 ip_filters
[filter_in
- 1].used
++;
1645 session
[s
].filter_in
= filter_in
;
1648 if (filter_out
>= 0)
1650 if (session
[s
].filter_out
)
1651 ip_filters
[session
[s
].filter_out
- 1].used
--;
1654 ip_filters
[filter_out
- 1].used
++;
1656 session
[s
].filter_out
= filter_out
;
1660 // start tidy shutdown of session
1661 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1663 int walled_garden
= session
[s
].walled_garden
;
1666 CSTAT(sessionshutdown
);
1668 if (!session
[s
].opened
)
1670 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1671 return; // not a live session
1674 if (!session
[s
].die
)
1676 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1677 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1678 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1681 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1683 // RADIUS Stop message
1684 uint16_t r
= radiusnew(s
);
1687 // stop, if not already trying
1688 if (radius
[r
].state
!= RADIUSSTOP
)
1690 radius
[r
].term_cause
= term_cause
;
1691 radius
[r
].term_msg
= reason
;
1692 radiussend(r
, RADIUSSTOP
);
1696 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1698 // Save counters to dump to accounting file
1699 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1700 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1704 { // IP allocated, clear and unroute
1707 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1709 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1710 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1713 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1714 session
[s
].route
[r
].ip
= 0;
1717 if (session
[s
].ip_pool_index
== -1) // static ip
1719 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1725 // unroute IPv6, if setup
1726 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
)
1727 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1730 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1731 throttle_session(s
, 0, 0);
1735 controlt
*c
= controlnew(14); // sending CDN
1739 *(uint16_t *) buf
= htons(cdn_result
);
1740 *(uint16_t *) (buf
+2) = htons(cdn_error
);
1741 controlb(c
, 1, buf
, 4, 1);
1744 control16(c
, 1, cdn_result
, 1);
1746 control16(c
, 14, s
, 1); // assigned session (our end)
1747 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
1750 if (!session
[s
].die
)
1751 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1753 // update filter refcounts
1754 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1755 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1758 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
1759 sess_local
[s
].lcp
.restart
= 0;
1760 sess_local
[s
].ipcp
.restart
= 0;
1761 sess_local
[s
].ipv6cp
.restart
= 0;
1762 sess_local
[s
].ccp
.restart
= 0;
1764 cluster_send_session(s
);
1767 void sendipcp(sessionidt s
, tunnelidt t
)
1769 uint8_t buf
[MAXETHER
];
1773 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
1775 if (!session
[s
].unique_id
)
1777 if (!++last_id
) ++last_id
; // skip zero
1778 session
[s
].unique_id
= last_id
;
1781 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
1785 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
1786 *(uint16_t *) (q
+ 2) = htons(10); // packet length
1787 q
[4] = 3; // ip address option
1788 q
[5] = 6; // option length
1789 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1790 config
->bind_address
? config
->bind_address
:
1791 my_address
; // send my IP
1793 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1794 restart_timer(s
, ipcp
);
1797 void sendipv6cp(sessionidt s
, tunnelidt t
)
1799 uint8_t buf
[MAXETHER
];
1803 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
1805 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
1809 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
1810 // only send one type
1812 *(uint16_t *) (q
+ 2) = htons(14);
1813 q
[4] = 1; // interface identifier option
1814 q
[5] = 10; // option length
1815 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
1816 *(uint32_t *) (q
+ 10) = 0;
1819 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
1820 restart_timer(s
, ipv6cp
);
1823 static void sessionclear(sessionidt s
)
1825 memset(&session
[s
], 0, sizeof(session
[s
]));
1826 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
1827 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
1829 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1830 session
[s
].next
= sessionfree
;
1834 // kill a session now
1835 void sessionkill(sessionidt s
, char *reason
)
1841 if (!session
[s
].opened
) // not alive
1844 if (session
[s
].next
)
1846 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
1850 session
[s
].die
= TIME
;
1851 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
1852 if (sess_local
[s
].radius
)
1853 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
1855 LOG(2, s
, session
[s
].tunnel
, "Kill session %u (%s): %s\n", s
, session
[s
].user
, reason
);
1856 if ((b
= session
[s
].bundle
))
1858 // This session was part of a bundle
1859 bundle
[b
].num_of_links
--;
1860 LOG(3, s
, 0, "MPPP: Dropping member link: %u from bundle %u\n", s
, b
);
1861 if (bundle
[b
].num_of_links
== 0)
1864 LOG(3, s
, 0, "MPPP: Kill bundle: %u (No remaing member links)\n", b
);
1868 // Adjust the members array to accomodate the new change
1869 uint8_t mem_num
= 0;
1870 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
1871 if (bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
1874 for (ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
1876 if (bundle
[b
].members
[ml
] == s
)
1882 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
1883 LOG(3, s
, 0, "MPPP: Adjusted member links array\n");
1886 cluster_send_bundle(b
);
1889 cluster_send_session(s
);
1892 static void tunnelclear(tunnelidt t
)
1895 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1896 tunnel
[t
].state
= TUNNELFREE
;
1899 static void bundleclear(bundleidt b
)
1902 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
1903 bundle
[b
].state
= BUNDLEFREE
;
1906 // kill a tunnel now
1907 static void tunnelkill(tunnelidt t
, char *reason
)
1914 tunnel
[t
].state
= TUNNELDIE
;
1916 // free control messages
1917 while ((c
= tunnel
[t
].controls
))
1919 controlt
* n
= c
->next
;
1920 tunnel
[t
].controls
= n
;
1921 tunnel
[t
].controlc
--;
1922 c
->next
= controlfree
;
1926 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1927 if (session
[s
].tunnel
== t
)
1928 sessionkill(s
, reason
);
1932 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
1933 cli_tunnel_actions
[t
].action
= 0;
1934 cluster_send_tunnel(t
);
1937 // shut down a tunnel cleanly
1938 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
1942 CSTAT(tunnelshutdown
);
1944 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1946 // never set up, can immediately kill
1947 tunnelkill(t
, reason
);
1950 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
1953 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1954 if (session
[s
].tunnel
== t
)
1955 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
1957 tunnel
[t
].state
= TUNNELDIE
;
1958 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
1959 cluster_send_tunnel(t
);
1960 // TBA - should we wait for sessions to stop?
1963 controlt
*c
= controlnew(4); // sending StopCCN
1968 *(uint16_t *) buf
= htons(result
);
1969 *(uint16_t *) (buf
+2) = htons(error
);
1972 int m
= strlen(msg
);
1973 if (m
+ 4 > sizeof(buf
))
1974 m
= sizeof(buf
) - 4;
1976 memcpy(buf
+4, msg
, m
);
1980 controlb(c
, 1, buf
, l
, 1);
1983 control16(c
, 1, result
, 1);
1985 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1986 controladd(c
, 0, t
); // send the message
1990 // read and process packet on tunnel (UDP)
1991 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
1993 uint8_t *chapresponse
= NULL
;
1994 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1995 uint8_t *p
= buf
+ 2;
2002 LOG_HEX(5, "UDP Data", buf
, len
);
2003 STAT(tunnel_rx_packets
);
2004 INC_STAT(tunnel_rx_bytes
, len
);
2007 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2008 STAT(tunnel_rx_errors
);
2011 if ((buf
[1] & 0x0F) != 2)
2013 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2014 STAT(tunnel_rx_errors
);
2019 l
= ntohs(*(uint16_t *) p
);
2022 t
= ntohs(*(uint16_t *) p
);
2024 s
= ntohs(*(uint16_t *) p
);
2026 if (s
>= MAXSESSION
)
2028 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2029 STAT(tunnel_rx_errors
);
2034 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2035 STAT(tunnel_rx_errors
);
2040 ns
= ntohs(*(uint16_t *) p
);
2042 nr
= ntohs(*(uint16_t *) p
);
2047 uint16_t o
= ntohs(*(uint16_t *) p
);
2052 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2053 STAT(tunnel_rx_errors
);
2058 // used to time out old tunnels
2059 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2060 tunnel
[t
].lastrec
= time_now
;
2064 uint16_t message
= 0xFFFF; // message type
2066 uint8_t mandatory
= 0;
2067 uint16_t asession
= 0; // assigned session
2068 uint32_t amagic
= 0; // magic number
2069 uint8_t aflags
= 0; // flags from last LCF
2070 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2071 char called
[MAXTEL
] = ""; // called number
2072 char calling
[MAXTEL
] = ""; // calling number
2074 if (!config
->cluster_iam_master
)
2076 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2080 // control messages must have bits 0x80|0x40|0x08
2081 // (type, length and sequence) set, and bits 0x02|0x01
2082 // (offset and priority) clear
2083 if ((*buf
& 0xCB) != 0xC8)
2085 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2086 STAT(tunnel_rx_errors
);
2090 // check for duplicate tunnel open message
2096 // Is this a duplicate of the first packet? (SCCRQ)
2098 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2100 if (tunnel
[i
].state
!= TUNNELOPENING
||
2101 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2102 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2105 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2110 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2111 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2113 // if no tunnel specified, assign one
2116 if (!(t
= new_tunnel()))
2118 LOG(1, 0, 0, "No more tunnels\n");
2119 STAT(tunnel_overflow
);
2123 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2124 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2125 tunnel
[t
].window
= 4; // default window
2126 STAT(tunnel_created
);
2127 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2128 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2131 // If the 'ns' just received is not the 'nr' we're
2132 // expecting, just send an ack and drop it.
2134 // if 'ns' is less, then we got a retransmitted packet.
2135 // if 'ns' is greater than missed a packet. Either way
2136 // we should ignore it.
2137 if (ns
!= tunnel
[t
].nr
)
2139 // is this the sequence we were expecting?
2140 STAT(tunnel_rx_errors
);
2141 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2142 t
, ns
, tunnel
[t
].nr
);
2144 if (l
) // Is this not a ZLB?
2149 // check sequence of this message
2151 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2152 // some to clear maybe?
2153 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2155 controlt
*c
= tunnel
[t
].controls
;
2156 tunnel
[t
].controls
= c
->next
;
2157 tunnel
[t
].controlc
--;
2158 c
->next
= controlfree
;
2161 tunnel
[t
].try = 0; // we have progress
2164 // receiver advance (do here so quoted correctly in any sends below)
2165 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2166 if (skip
< 0) skip
= 0;
2167 if (skip
< tunnel
[t
].controlc
)
2169 // some control packets can now be sent that were previous stuck out of window
2170 int tosend
= tunnel
[t
].window
- skip
;
2171 controlt
*c
= tunnel
[t
].controls
;
2179 tunnel
[t
].try = 0; // first send
2180 tunnelsend(c
->buf
, c
->length
, t
);
2185 if (!tunnel
[t
].controlc
)
2186 tunnel
[t
].retry
= 0; // caught up
2189 { // if not a null message
2194 // Default disconnect cause/message on receipt of CDN. Set to
2195 // more specific value from attribute 1 (result code) or 46
2196 // (disconnect cause) if present below.
2197 int disc_cause_set
= 0;
2198 int disc_cause
= TERM_NAS_REQUEST
;
2199 char const *disc_reason
= "Closed (Received CDN).";
2202 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2204 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2211 LOG(1, s
, t
, "Invalid length in AVP\n");
2212 STAT(tunnel_rx_errors
);
2217 if (flags
& 0x3C) // reserved bits, should be clear
2219 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2221 result
= 2; // general error
2222 error
= 3; // reserved field non-zero
2227 if (*(uint16_t *) (b
))
2229 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2231 result
= 2; // general error
2232 error
= 6; // generic vendor-specific error
2233 msg
= "unsupported vendor-specific";
2237 mtype
= ntohs(*(uint16_t *) (b
));
2245 // handle hidden AVPs
2246 if (!*config
->l2tp_secret
)
2248 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2250 result
= 2; // general error
2251 error
= 6; // generic vendor-specific error
2252 msg
= "secret not specified";
2255 if (!session
[s
].random_vector_length
)
2257 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2259 result
= 2; // general error
2260 error
= 6; // generic
2261 msg
= "no random vector";
2266 LOG(2, s
, t
, "Short hidden AVP.\n");
2268 result
= 2; // general error
2269 error
= 2; // length is wrong
2275 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2277 orig_len
= ntohs(*(uint16_t *) b
);
2278 if (orig_len
> n
+ 2)
2280 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2284 result
= 2; // general error
2285 error
= 2; // length is wrong
2294 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2295 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2299 case 0: // message type
2300 message
= ntohs(*(uint16_t *) b
);
2301 mandatory
= flags
& 0x80;
2302 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2304 case 1: // result code
2306 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2307 char const *resdesc
= "(unknown)";
2308 char const *errdesc
= NULL
;
2313 resdesc
= l2tp_stopccn_result_code(rescode
);
2314 cause
= TERM_LOST_SERVICE
;
2316 else if (message
== 14)
2318 resdesc
= l2tp_cdn_result_code(rescode
);
2320 cause
= TERM_LOST_CARRIER
;
2322 cause
= TERM_ADMIN_RESET
;
2325 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2328 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2329 errdesc
= l2tp_error_code(errcode
);
2330 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2333 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2335 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2337 disc_cause_set
= mtype
;
2338 disc_reason
= errdesc
? errdesc
: resdesc
;
2345 case 2: // protocol version
2347 version
= ntohs(*(uint16_t *) (b
));
2348 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2349 if (version
&& version
!= 0x0100)
2350 { // allow 0.0 and 1.0
2351 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2353 result
= 5; // unspported protocol version
2354 error
= 0x0100; // supported version
2360 case 3: // framing capabilities
2362 case 4: // bearer capabilities
2364 case 5: // tie breaker
2365 // We never open tunnels, so we don't care about tie breakers
2367 case 6: // firmware revision
2369 case 7: // host name
2370 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2371 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2372 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2373 // TBA - to send to RADIUS
2375 case 8: // vendor name
2376 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2377 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2378 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2380 case 9: // assigned tunnel
2381 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2382 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2384 case 10: // rx window
2385 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2386 if (!tunnel
[t
].window
)
2387 tunnel
[t
].window
= 1; // window of 0 is silly
2388 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2390 case 11: // Challenge
2392 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2393 build_chap_response(b
, 2, n
, &chapresponse
);
2396 case 13: // Response
2397 // Why did they send a response? We never challenge.
2398 LOG(2, s
, t
, " received unexpected challenge response\n");
2401 case 14: // assigned session
2402 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2403 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2405 case 15: // call serial number
2406 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2408 case 18: // bearer type
2409 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2412 case 19: // framing type
2413 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2416 case 21: // called number
2417 memset(called
, 0, sizeof(called
));
2418 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2419 LOG(4, s
, t
, " Called <%s>\n", called
);
2421 case 22: // calling number
2422 memset(calling
, 0, sizeof(calling
));
2423 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2424 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2428 case 24: // tx connect speed
2431 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2435 // AS5300s send connect speed as a string
2437 memset(tmp
, 0, sizeof(tmp
));
2438 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2439 session
[s
].tx_connect_speed
= atol(tmp
);
2441 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2443 case 38: // rx connect speed
2446 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2450 // AS5300s send connect speed as a string
2452 memset(tmp
, 0, sizeof(tmp
));
2453 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2454 session
[s
].rx_connect_speed
= atol(tmp
);
2456 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2458 case 25: // Physical Channel ID
2460 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2461 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2464 case 29: // Proxy Authentication Type
2466 uint16_t atype
= ntohs(*(uint16_t *)b
);
2467 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2470 case 30: // Proxy Authentication Name
2473 memset(authname
, 0, sizeof(authname
));
2474 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2475 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2479 case 31: // Proxy Authentication Challenge
2481 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2484 case 32: // Proxy Authentication ID
2486 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2487 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2490 case 33: // Proxy Authentication Response
2491 LOG(4, s
, t
, " Proxy Auth Response\n");
2493 case 27: // last sent lcp
2494 { // find magic number
2495 uint8_t *p
= b
, *e
= p
+ n
;
2496 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2498 if (*p
== 5 && p
[1] == 6) // Magic-Number
2499 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2500 else if (*p
== 7) // Protocol-Field-Compression
2501 aflags
|= SESSION_PFC
;
2502 else if (*p
== 8) // Address-and-Control-Field-Compression
2503 aflags
|= SESSION_ACFC
;
2508 case 28: // last recv lcp confreq
2510 case 26: // Initial Received LCP CONFREQ
2512 case 39: // seq required - we control it as an LNS anyway...
2514 case 36: // Random Vector
2515 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2516 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2517 if (n
> sizeof(session
[s
].random_vector
))
2518 n
= sizeof(session
[s
].random_vector
);
2519 memcpy(session
[s
].random_vector
, b
, n
);
2520 session
[s
].random_vector_length
= n
;
2522 case 46: // ppp disconnect cause
2525 uint16_t code
= ntohs(*(uint16_t *) b
);
2526 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2527 uint8_t dir
= *(b
+ 4);
2529 LOG(4, s
, t
, " PPP disconnect cause "
2530 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2531 code
, proto
, dir
, n
- 5, b
+ 5);
2533 disc_cause_set
= mtype
;
2537 case 1: // admin disconnect
2538 disc_cause
= TERM_ADMIN_RESET
;
2539 disc_reason
= "Administrative disconnect";
2541 case 3: // lcp terminate
2542 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2543 disc_cause
= TERM_USER_REQUEST
;
2544 disc_reason
= "Normal disconnection";
2546 case 4: // compulsory encryption unavailable
2547 if (dir
!= 1) break; // 1=refused by peer, 2=local
2548 disc_cause
= TERM_USER_ERROR
;
2549 disc_reason
= "Compulsory encryption refused";
2551 case 5: // lcp: fsm timeout
2552 disc_cause
= TERM_PORT_ERROR
;
2553 disc_reason
= "LCP: FSM timeout";
2555 case 6: // lcp: no recognisable lcp packets received
2556 disc_cause
= TERM_PORT_ERROR
;
2557 disc_reason
= "LCP: no recognisable LCP packets";
2559 case 7: // lcp: magic-no error (possibly looped back)
2560 disc_cause
= TERM_PORT_ERROR
;
2561 disc_reason
= "LCP: magic-no error (possible loop)";
2563 case 8: // lcp: echo request timeout
2564 disc_cause
= TERM_PORT_ERROR
;
2565 disc_reason
= "LCP: echo request timeout";
2567 case 13: // auth: fsm timeout
2568 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2569 disc_reason
= "Authentication: FSM timeout";
2571 case 15: // auth: unacceptable auth protocol
2572 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2573 disc_reason
= "Unacceptable authentication protocol";
2575 case 16: // auth: authentication failed
2576 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2577 disc_reason
= "Authentication failed";
2579 case 17: // ncp: fsm timeout
2580 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2581 disc_reason
= "NCP: FSM timeout";
2583 case 18: // ncp: no ncps available
2584 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2585 disc_reason
= "NCP: no NCPs available";
2587 case 19: // ncp: failure to converge on acceptable address
2588 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2589 disc_reason
= (dir
== 1)
2590 ? "NCP: too many Configure-Naks received from peer"
2591 : "NCP: too many Configure-Naks sent to peer";
2593 case 20: // ncp: user not permitted to use any address
2594 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2595 disc_reason
= (dir
== 1)
2596 ? "NCP: local link address not acceptable to peer"
2597 : "NCP: remote link address not acceptable";
2604 static char e
[] = "unknown AVP 0xXXXX";
2605 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2607 result
= 2; // general error
2608 error
= 8; // unknown mandatory AVP
2609 sprintf((msg
= e
) + 14, "%04x", mtype
);
2616 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2620 case 1: // SCCRQ - Start Control Connection Request
2621 tunnel
[t
].state
= TUNNELOPENING
;
2622 if (main_quit
!= QUIT_SHUTDOWN
)
2624 controlt
*c
= controlnew(2); // sending SCCRP
2625 control16(c
, 2, version
, 1); // protocol version
2626 control32(c
, 3, 3, 1); // framing
2627 controls(c
, 7, hostname
, 1); // host name
2628 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2629 control16(c
, 9, t
, 1); // assigned tunnel
2630 controladd(c
, 0, t
); // send the resply
2634 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2638 tunnel
[t
].state
= TUNNELOPEN
;
2641 tunnel
[t
].state
= TUNNELOPEN
;
2642 controlnull(t
); // ack
2645 controlnull(t
); // ack
2646 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2649 controlnull(t
); // simply ACK
2661 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2663 controlt
*c
= controlnew(11); // ICRP
2666 sessionfree
= session
[s
].next
;
2667 memset(&session
[s
], 0, sizeof(session
[s
]));
2669 if (s
> config
->cluster_highest_sessionid
)
2670 config
->cluster_highest_sessionid
= s
;
2672 session
[s
].opened
= time_now
;
2673 session
[s
].tunnel
= t
;
2674 session
[s
].far
= asession
;
2675 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2676 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2677 control16(c
, 14, s
, 1); // assigned session
2678 controladd(c
, asession
, t
); // send the reply
2680 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2681 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2683 session
[s
].ppp
.phase
= Establish
;
2684 session
[s
].ppp
.lcp
= Starting
;
2686 STAT(session_created
);
2691 controlt
*c
= controlnew(14); // CDN
2694 STAT(session_overflow
);
2695 LOG(1, 0, t
, "No free sessions\n");
2696 control16(c
, 1, 4, 0); // temporary lack of resources
2699 control16(c
, 1, 2, 7); // shutting down, try another
2701 controladd(c
, asession
, t
); // send the message
2708 if (amagic
== 0) amagic
= time_now
;
2709 session
[s
].magic
= amagic
; // set magic number
2710 session
[s
].flags
= aflags
; // set flags received
2711 session
[s
].mru
= PPPoE_MRU
; // default
2712 controlnull(t
); // ack
2715 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
2716 sess_local
[s
].ppp_mru
= MRU
;
2718 // Set multilink options before sending initial LCP packet
2719 sess_local
[s
].mp_mrru
= 1614;
2720 sess_local
[s
].mp_epdis
= config
->bind_address
? config
->bind_address
: my_address
;
2723 change_state(s
, lcp
, RequestSent
);
2727 controlnull(t
); // ack
2728 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
2731 LOG(1, s
, t
, "Missing message type\n");
2734 STAT(tunnel_rx_errors
);
2736 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2738 LOG(1, s
, t
, "Unknown message type %u\n", message
);
2741 if (chapresponse
) free(chapresponse
);
2742 cluster_send_tunnel(t
);
2746 LOG(4, s
, t
, " Got a ZLB ack\n");
2753 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
2754 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
2755 { // HDLC address header, discard
2761 LOG(1, s
, t
, "Short ppp length %d\n", l
);
2762 STAT(tunnel_rx_errors
);
2772 proto
= ntohs(*(uint16_t *) p
);
2777 if (s
&& !session
[s
].opened
) // Is something wrong??
2779 if (!config
->cluster_iam_master
)
2781 // Pass it off to the master to deal with..
2782 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2787 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
2788 STAT(tunnel_rx_errors
);
2792 if (proto
== PPPPAP
)
2794 session
[s
].last_packet
= time_now
;
2795 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2796 processpap(s
, t
, p
, l
);
2798 else if (proto
== PPPCHAP
)
2800 session
[s
].last_packet
= time_now
;
2801 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2802 processchap(s
, t
, p
, l
);
2804 else if (proto
== PPPLCP
)
2806 session
[s
].last_packet
= time_now
;
2807 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2808 processlcp(s
, t
, p
, l
);
2810 else if (proto
== PPPIPCP
)
2812 session
[s
].last_packet
= time_now
;
2813 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2814 processipcp(s
, t
, p
, l
);
2816 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
2818 session
[s
].last_packet
= time_now
;
2819 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2820 processipv6cp(s
, t
, p
, l
);
2822 else if (proto
== PPPCCP
)
2824 session
[s
].last_packet
= time_now
;
2825 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2826 processccp(s
, t
, p
, l
);
2828 else if (proto
== PPPIP
)
2832 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2833 return; // closing session, PPP not processed
2836 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2837 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2839 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2843 processipin(s
, t
, p
, l
);
2845 else if (proto
== PPPMP
)
2849 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2850 return; // closing session, PPP not processed
2853 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2854 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2856 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2860 processmpin(s
, t
, p
, l
);
2862 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
2866 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2867 return; // closing session, PPP not processed
2870 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2871 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2873 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2877 processipv6in(s
, t
, p
, l
);
2879 else if (session
[s
].ppp
.lcp
== Opened
)
2881 session
[s
].last_packet
= time_now
;
2882 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2883 protoreject(s
, t
, p
, l
, proto
);
2887 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
2888 proto
, ppp_state(session
[s
].ppp
.lcp
));
2893 // read and process packet on tun
2894 static void processtun(uint8_t * buf
, int len
)
2896 LOG_HEX(5, "Receive TUN Data", buf
, len
);
2897 STAT(tun_rx_packets
);
2898 INC_STAT(tun_rx_bytes
, len
);
2906 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
2907 STAT(tun_rx_errors
);
2911 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
2912 processipout(buf
, len
);
2913 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
2914 && config
->ipv6_prefix
.s6_addr
[0])
2915 processipv6out(buf
, len
);
2920 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
2921 // that we look at the whole of the tunnel, radius and session tables
2923 static void regular_cleanups(double period
)
2925 // Next tunnel, radius and session to check for actions on.
2926 static tunnelidt t
= 0;
2928 static sessionidt s
= 0;
2941 // divide up tables into slices based on the last run
2942 t_slice
= config
->cluster_highest_tunnelid
* period
;
2943 r_slice
= (MAXRADIUS
- 1) * period
;
2944 s_slice
= config
->cluster_highest_sessionid
* period
;
2948 else if (t_slice
> config
->cluster_highest_tunnelid
)
2949 t_slice
= config
->cluster_highest_tunnelid
;
2953 else if (r_slice
> (MAXRADIUS
- 1))
2954 r_slice
= MAXRADIUS
- 1;
2958 else if (s_slice
> config
->cluster_highest_sessionid
)
2959 s_slice
= config
->cluster_highest_sessionid
;
2961 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
2963 for (i
= 0; i
< t_slice
; i
++)
2966 if (t
> config
->cluster_highest_tunnelid
)
2969 // check for expired tunnels
2970 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2972 STAT(tunnel_timeout
);
2973 tunnelkill(t
, "Expired");
2977 // check for message resend
2978 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2980 // resend pending messages as timeout on reply
2981 if (tunnel
[t
].retry
<= TIME
)
2983 controlt
*c
= tunnel
[t
].controls
;
2984 uint8_t w
= tunnel
[t
].window
;
2985 tunnel
[t
].try++; // another try
2986 if (tunnel
[t
].try > 5)
2987 tunnelkill(t
, "Timeout on control message"); // game over
2991 tunnelsend(c
->buf
, c
->length
, t
);
2999 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3001 controlt
*c
= controlnew(6); // sending HELLO
3002 controladd(c
, 0, t
); // send the message
3003 LOG(3, 0, t
, "Sending HELLO message\n");
3007 // Check for tunnel changes requested from the CLI
3008 if ((a
= cli_tunnel_actions
[t
].action
))
3010 cli_tunnel_actions
[t
].action
= 0;
3011 if (a
& CLI_TUN_KILL
)
3013 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3014 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3020 for (i
= 0; i
< r_slice
; i
++)
3026 if (!radius
[r
].state
)
3029 if (radius
[r
].retry
<= TIME
)
3036 for (i
= 0; i
< s_slice
; i
++)
3039 if (s
> config
->cluster_highest_sessionid
)
3042 if (!session
[s
].opened
) // Session isn't in use
3045 // check for expired sessions
3048 if (session
[s
].die
<= TIME
)
3050 sessionkill(s
, "Expired");
3056 // check for timed out sessions
3057 if (session
[s
].timeout
)
3059 bundleidt bid
= session
[s
].bundle
;
3062 clockt curr_time
= time_now
;
3063 if (curr_time
- bundle
[bid
].last_check
>= 1)
3065 bundle
[bid
].online_time
+= (curr_time
-bundle
[bid
].last_check
)*bundle
[bid
].num_of_links
;
3066 bundle
[bid
].last_check
= curr_time
;
3067 if (bundle
[bid
].online_time
>= session
[s
].timeout
)
3070 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3072 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3079 else if (session
[s
].timeout
<= time_now
- session
[s
].opened
)
3081 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3088 if (sess_local
[s
].lcp
.restart
<= time_now
)
3090 int next_state
= session
[s
].ppp
.lcp
;
3091 switch (session
[s
].ppp
.lcp
)
3095 next_state
= RequestSent
;
3098 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3100 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3101 sendlcp(s
, session
[s
].tunnel
);
3102 change_state(s
, lcp
, next_state
);
3106 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3107 STAT(session_timeout
);
3117 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3119 int next_state
= session
[s
].ppp
.ipcp
;
3120 switch (session
[s
].ppp
.ipcp
)
3124 next_state
= RequestSent
;
3127 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3129 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3130 sendipcp(s
, session
[s
].tunnel
);
3131 change_state(s
, ipcp
, next_state
);
3135 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3136 STAT(session_timeout
);
3146 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3148 int next_state
= session
[s
].ppp
.ipv6cp
;
3149 switch (session
[s
].ppp
.ipv6cp
)
3153 next_state
= RequestSent
;
3156 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3158 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3159 sendipv6cp(s
, session
[s
].tunnel
);
3160 change_state(s
, ipv6cp
, next_state
);
3164 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3165 change_state(s
, ipv6cp
, Stopped
);
3172 if (sess_local
[s
].ccp
.restart
<= time_now
)
3174 int next_state
= session
[s
].ppp
.ccp
;
3175 switch (session
[s
].ppp
.ccp
)
3179 next_state
= RequestSent
;
3182 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3184 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3185 sendccp(s
, session
[s
].tunnel
);
3186 change_state(s
, ccp
, next_state
);
3190 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3191 change_state(s
, ccp
, Stopped
);
3198 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3199 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3201 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3202 STAT(session_timeout
);
3207 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3208 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3209 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3211 uint8_t b
[MAXETHER
];
3213 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3217 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3218 *(uint16_t *)(q
+ 2) = htons(8); // Length
3219 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3221 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3222 (int)(time_now
- session
[s
].last_packet
));
3223 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3224 sess_local
[s
].last_echo
= time_now
;
3228 // Drop sessions who have reached session_timeout seconds
3229 if (session
[s
].session_timeout
&& (time_now
- session
[s
].opened
>= session
[s
].session_timeout
))
3231 sessionshutdown(s
, "Session Timeout Reached", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3232 STAT(session_timeout
);
3237 // Drop sessions who have reached idle_timeout seconds
3238 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3240 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3241 STAT(session_timeout
);
3246 // Check for actions requested from the CLI
3247 if ((a
= cli_session_actions
[s
].action
))
3251 cli_session_actions
[s
].action
= 0;
3252 if (a
& CLI_SESS_KILL
)
3254 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3255 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3256 a
= 0; // dead, no need to check for other actions
3260 if (a
& CLI_SESS_NOSNOOP
)
3262 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3263 session
[s
].snoop_ip
= 0;
3264 session
[s
].snoop_port
= 0;
3268 else if (a
& CLI_SESS_SNOOP
)
3270 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3271 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3272 cli_session_actions
[s
].snoop_port
);
3274 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3275 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3280 if (a
& CLI_SESS_NOTHROTTLE
)
3282 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3283 throttle_session(s
, 0, 0);
3287 else if (a
& CLI_SESS_THROTTLE
)
3289 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3290 cli_session_actions
[s
].throttle_in
,
3291 cli_session_actions
[s
].throttle_out
);
3293 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3298 if (a
& CLI_SESS_NOFILTER
)
3300 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3301 filter_session(s
, 0, 0);
3305 else if (a
& CLI_SESS_FILTER
)
3307 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3308 cli_session_actions
[s
].filter_in
,
3309 cli_session_actions
[s
].filter_out
);
3311 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3317 cluster_send_session(s
);
3320 // RADIUS interim accounting
3321 if (config
->radius_accounting
&& config
->radius_interim
> 0
3322 && session
[s
].ip
&& !session
[s
].walled_garden
3323 && !sess_local
[s
].radius
// RADIUS already in progress
3324 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
)
3326 int rad
= radiusnew(s
);
3329 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3330 STAT(radius_overflow
);
3334 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3335 session
[s
].user
, session
[s
].unique_id
);
3337 radiussend(rad
, RADIUSINTERIM
);
3338 sess_local
[s
].last_interim
= time_now
;
3343 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3344 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3348 // Are we in the middle of a tunnel update, or radius
3351 static int still_busy(void)
3354 static clockt last_talked
= 0;
3355 static clockt start_busy_wait
= 0;
3357 if (!config
->cluster_iam_master
)
3360 static time_t stopped_bgp
= 0;
3365 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3367 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3368 if (bgp_peers
[i
].state
== Established
)
3369 bgp_stop(&bgp_peers
[i
]);
3371 stopped_bgp
= time_now
;
3373 // we don't want to become master
3374 cluster_send_ping(0);
3379 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
3387 if (main_quit
== QUIT_SHUTDOWN
)
3389 static int dropped
= 0;
3394 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3395 for (i
= 1; i
< MAXTUNNEL
; i
++)
3396 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3397 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3403 if (start_busy_wait
== 0)
3404 start_busy_wait
= TIME
;
3406 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3408 if (!tunnel
[i
].controlc
)
3411 if (last_talked
!= TIME
)
3413 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3419 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3420 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3422 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3426 for (i
= 1; i
< MAXRADIUS
; i
++)
3428 if (radius
[i
].state
== RADIUSNULL
)
3430 if (radius
[i
].state
== RADIUSWAIT
)
3433 if (last_talked
!= TIME
)
3435 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3445 # include <sys/epoll.h>
3447 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3448 # include "fake_epoll.h"
3451 // the base set of fds polled: cli, cluster, tun, udp, control, dae
3454 // additional polled fds
3456 # define EXTRA_FDS BGP_NUM_PEERS
3458 # define EXTRA_FDS 0
3461 // main loop - gets packets on tun or udp and processes them
3462 static void mainloop(void)
3466 clockt next_cluster_ping
= 0; // send initial ping immediately
3467 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3468 int maxevent
= sizeof(events
)/sizeof(*events
);
3470 if ((epollfd
= epoll_create(maxevent
)) < 0)
3472 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3476 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d\n",
3477 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
);
3479 /* setup our fds to poll for input */
3481 static struct event_data d
[BASE_FDS
];
3482 struct epoll_event e
;
3489 d
[i
].type
= FD_TYPE_CLI
;
3490 e
.data
.ptr
= &d
[i
++];
3491 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3494 d
[i
].type
= FD_TYPE_CLUSTER
;
3495 e
.data
.ptr
= &d
[i
++];
3496 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3498 d
[i
].type
= FD_TYPE_TUN
;
3499 e
.data
.ptr
= &d
[i
++];
3500 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3502 d
[i
].type
= FD_TYPE_UDP
;
3503 e
.data
.ptr
= &d
[i
++];
3504 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3506 d
[i
].type
= FD_TYPE_CONTROL
;
3507 e
.data
.ptr
= &d
[i
++];
3508 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3510 d
[i
].type
= FD_TYPE_DAE
;
3511 e
.data
.ptr
= &d
[i
++];
3512 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3516 signal(SIGPIPE
, SIG_IGN
);
3517 bgp_setup(config
->as_number
);
3518 if (config
->bind_address
)
3519 bgp_add_route(config
->bind_address
, 0xffffffff);
3521 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3523 if (config
->neighbour
[i
].name
[0])
3524 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3525 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3526 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3530 while (!main_quit
|| still_busy())
3540 config
->reload_config
++;
3543 if (config
->reload_config
)
3545 config
->reload_config
= 0;
3553 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3554 STAT(select_called
);
3559 if (errno
== EINTR
||
3560 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3563 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3569 struct sockaddr_in addr
;
3570 struct in_addr local
;
3575 int cluster_ready
= 0;
3578 int cluster_pkts
= 0;
3580 uint32_t bgp_events
[BGP_NUM_PEERS
];
3581 memset(bgp_events
, 0, sizeof(bgp_events
));
3584 for (c
= n
, i
= 0; i
< c
; i
++)
3586 struct event_data
*d
= events
[i
].data
.ptr
;
3590 case FD_TYPE_CLI
: // CLI connections
3594 alen
= sizeof(addr
);
3595 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3601 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3607 // these are handled below, with multiple interleaved reads
3608 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3609 case FD_TYPE_TUN
: tun_ready
++; break;
3610 case FD_TYPE_UDP
: udp_ready
++; break;
3612 case FD_TYPE_CONTROL
: // nsctl commands
3613 alen
= sizeof(addr
);
3614 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3615 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3619 case FD_TYPE_DAE
: // DAE requests
3620 alen
= sizeof(addr
);
3621 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3622 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3626 case FD_TYPE_RADIUS
: // RADIUS response
3627 alen
= sizeof(addr
);
3628 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3629 if (s
>= 0 && config
->cluster_iam_master
)
3631 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3632 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3633 processrad(buf
, s
, d
->index
);
3635 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3636 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3644 bgp_events
[d
->index
] = events
[i
].events
;
3650 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3655 bgp_process(bgp_events
);
3658 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3663 alen
= sizeof(addr
);
3664 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3666 processudp(buf
, s
, &addr
);
3679 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3694 alen
= sizeof(addr
);
3695 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3697 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3708 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3709 STAT(multi_read_used
);
3711 if (c
>= config
->multi_read_count
)
3713 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3714 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3716 STAT(multi_read_exceeded
);
3723 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
3725 // Log current traffic stats
3726 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3727 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3728 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
3729 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
3730 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
3732 udp_tx
= udp_rx
= 0;
3733 udp_rx_pkt
= eth_rx_pkt
= 0;
3734 eth_tx
= eth_rx
= 0;
3737 if (config
->dump_speed
)
3738 printf("%s\n", config
->bandwidth
);
3740 // Update the internal time counter
3741 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3745 struct param_timer p
= { time_now
};
3746 run_plugins(PLUGIN_TIMER
, &p
);
3750 // Runs on every machine (master and slaves).
3751 if (next_cluster_ping
<= TIME
)
3753 // Check to see which of the cluster is still alive..
3755 cluster_send_ping(basetime
); // Only does anything if we're a slave
3756 cluster_check_master(); // ditto.
3758 cluster_heartbeat(); // Only does anything if we're a master.
3759 cluster_check_slaves(); // ditto.
3761 master_update_counts(); // If we're a slave, send our byte counters to our master.
3763 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
3764 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
3766 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
3769 if (!config
->cluster_iam_master
)
3772 // Run token bucket filtering queue..
3773 // Only run it every 1/10th of a second.
3775 static clockt last_run
= 0;
3776 if (last_run
!= TIME
)
3783 // Handle timeouts, retries etc.
3785 static double last_clean
= 0;
3789 TIME
= now(&this_clean
);
3790 diff
= this_clean
- last_clean
;
3792 // Run during idle time (after we've handled
3793 // all incoming packets) or every 1/10th sec
3794 if (!more
|| diff
> 0.1)
3796 regular_cleanups(diff
);
3797 last_clean
= this_clean
;
3801 if (*config
->accounting_dir
)
3803 static clockt next_acct
= 0;
3804 static clockt next_shut_acct
= 0;
3806 if (next_acct
<= TIME
)
3808 // Dump accounting data
3809 next_acct
= TIME
+ ACCT_TIME
;
3810 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3813 else if (next_shut_acct
<= TIME
)
3815 // Dump accounting data for shutdown sessions
3816 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3823 // Are we the master and shutting down??
3824 if (config
->cluster_iam_master
)
3825 cluster_heartbeat(); // Flush any queued changes..
3827 // Ok. Notify everyone we're shutting down. If we're
3828 // the master, this will force an election.
3829 cluster_send_ping(0);
3832 // Important!!! We MUST not process any packets past this point!
3833 LOG(1, 0, 0, "Shutdown complete\n");
3836 static void stripdomain(char *host
)
3840 if ((p
= strchr(host
, '.')))
3846 FILE *resolv
= fopen("/etc/resolv.conf", "r");
3852 while (fgets(buf
, sizeof(buf
), resolv
))
3854 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
3857 if (!isspace(buf
[6]))
3861 while (isspace(*b
)) b
++;
3866 while (*b
&& !isspace(*b
)) b
++;
3868 if (buf
[0] == 'd') // domain is canonical
3874 // first search line
3877 // hold, may be subsequent domain line
3878 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
3889 int hl
= strlen(host
);
3890 int dl
= strlen(domain
);
3891 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
3892 host
[hl
-dl
- 1] = 0;
3896 *p
= 0; // everything after first dot
3901 // Init data structures
3902 static void initdata(int optdebug
, char *optconfig
)
3906 if (!(config
= shared_malloc(sizeof(configt
))))
3908 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
3912 memset(config
, 0, sizeof(configt
));
3913 time(&config
->start_time
);
3914 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
3915 config
->debug
= optdebug
;
3916 config
->num_tbfs
= MAXTBFS
;
3917 config
->rl_rate
= 28; // 28kbps
3918 config
->cluster_mcast_ttl
= 1;
3919 config
->cluster_master_min_adv
= 1;
3920 config
->ppp_restart_time
= 3;
3921 config
->ppp_max_configure
= 10;
3922 config
->ppp_max_failure
= 5;
3923 strcpy(config
->random_device
, RANDOMDEVICE
);
3925 log_stream
= stderr
;
3928 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
3930 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
3933 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
3936 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
3938 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
3941 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
3943 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
3946 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
3948 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
3951 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
3953 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
3956 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
3958 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
3962 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
3964 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
3968 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
3970 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
3974 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
3976 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
3980 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
3982 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
3985 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
3987 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
3989 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
3992 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
3994 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
3996 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
3999 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4001 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4002 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4003 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4004 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4005 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4007 // Put all the sessions on the free list marked as undefined.
4008 for (i
= 1; i
< MAXSESSION
; i
++)
4010 session
[i
].next
= i
+ 1;
4011 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4013 session
[MAXSESSION
- 1].next
= 0;
4016 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4017 for (i
= 1; i
< MAXTUNNEL
; i
++)
4018 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4020 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4021 bundle
[i
].state
= BUNDLEUNDEF
;
4026 // Grab my hostname unless it's been specified
4027 gethostname(hostname
, sizeof(hostname
));
4028 stripdomain(hostname
);
4031 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4034 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4036 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4042 static int assign_ip_address(sessionidt s
)
4046 time_t best_time
= time_now
;
4047 char *u
= session
[s
].user
;
4051 CSTAT(assign_ip_address
);
4053 for (i
= 1; i
< ip_pool_size
; i
++)
4055 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4058 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4065 if (ip_address_pool
[i
].last
< best_time
)
4068 if (!(best_time
= ip_address_pool
[i
].last
))
4069 break; // never used, grab this one
4075 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4079 session
[s
].ip
= ip_address_pool
[best
].address
;
4080 session
[s
].ip_pool_index
= best
;
4081 ip_address_pool
[best
].assigned
= 1;
4082 ip_address_pool
[best
].last
= time_now
;
4083 ip_address_pool
[best
].session
= s
;
4084 if (session
[s
].walled_garden
)
4085 /* Don't track addresses of users in walled garden (note: this
4086 means that their address isn't "sticky" even if they get
4088 ip_address_pool
[best
].user
[0] = 0;
4090 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4093 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4094 reuse
? "Reusing" : "Allocating", best
);
4099 static void free_ip_address(sessionidt s
)
4101 int i
= session
[s
].ip_pool_index
;
4104 CSTAT(free_ip_address
);
4107 return; // what the?
4109 if (i
< 0) // Is this actually part of the ip pool?
4113 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4115 ip_address_pool
[i
].assigned
= 0;
4116 ip_address_pool
[i
].session
= 0;
4117 ip_address_pool
[i
].last
= time_now
;
4121 // Fsck the address pool against the session table.
4122 // Normally only called when we become a master.
4124 // This isn't perfect: We aren't keep tracking of which
4125 // users used to have an IP address.
4127 void rebuild_address_pool(void)
4132 // Zero the IP pool allocation, and build
4133 // a map from IP address to pool index.
4134 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4136 ip_address_pool
[i
].assigned
= 0;
4137 ip_address_pool
[i
].session
= 0;
4138 if (!ip_address_pool
[i
].address
)
4141 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4144 for (i
= 0; i
< MAXSESSION
; ++i
)
4147 if (!(session
[i
].opened
&& session
[i
].ip
))
4150 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4152 if (session
[i
].ip_pool_index
< 0)
4154 // Not allocated out of the pool.
4155 if (ipid
< 1) // Not found in the pool either? good.
4158 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4159 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4161 // Fall through and process it as part of the pool.
4165 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4167 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4169 session
[i
].ip_pool_index
= ipid
;
4173 ip_address_pool
[ipid
].assigned
= 1;
4174 ip_address_pool
[ipid
].session
= i
;
4175 ip_address_pool
[ipid
].last
= time_now
;
4176 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4177 session
[i
].ip_pool_index
= ipid
;
4178 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4183 // Fix the address pool to match a changed session.
4184 // (usually when the master sends us an update).
4185 static void fix_address_pool(int sid
)
4189 ipid
= session
[sid
].ip_pool_index
;
4191 if (ipid
> ip_pool_size
)
4192 return; // Ignore it. rebuild_address_pool will fix it up.
4194 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4195 return; // Just ignore it. rebuild_address_pool will take care of it.
4197 ip_address_pool
[ipid
].assigned
= 1;
4198 ip_address_pool
[ipid
].session
= sid
;
4199 ip_address_pool
[ipid
].last
= time_now
;
4200 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4204 // Add a block of addresses to the IP pool to hand out.
4206 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
4210 mask
= 0xffffffff; // Host route only.
4214 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4217 for (i
= addr
;(i
& mask
) == addr
; ++i
)
4219 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4220 continue; // Skip 0 and broadcast addresses.
4222 ip_address_pool
[ip_pool_size
].address
= i
;
4223 ip_address_pool
[ip_pool_size
].assigned
= 0;
4225 if (ip_pool_size
>= MAXIPPOOL
)
4227 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4233 // Initialize the IP address pool
4234 static void initippool()
4239 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4241 if (!(f
= fopen(IPPOOLFILE
, "r")))
4243 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4247 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4250 buf
[4095] = 0; // Force it to be zero terminated/
4252 if (*buf
== '#' || *buf
== '\n')
4253 continue; // Skip comments / blank lines
4254 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4255 if ((p
= (char *)strchr(buf
, ':')))
4259 src
= inet_addr(buf
);
4260 if (src
== INADDR_NONE
)
4262 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4265 // This entry is for a specific IP only
4266 if (src
!= config
->bind_address
)
4271 if ((p
= (char *)strchr(pool
, '/')))
4275 in_addr_t start
= 0, mask
= 0;
4277 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4279 if (!*p
|| !(numbits
= atoi(p
)))
4281 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4284 start
= ntohl(inet_addr(pool
));
4285 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
4287 // Add a static route for this pool
4288 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
4289 fmtaddr(htonl(start
), 0), 32 + mask
);
4291 routeset(0, start
, mask
, 0, 1);
4293 add_to_ip_pool(start
, mask
);
4297 // It's a single ip address
4298 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4302 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4305 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4307 struct sockaddr_in snoop_addr
= {0};
4308 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4311 snoop_addr
.sin_family
= AF_INET
;
4312 snoop_addr
.sin_addr
.s_addr
= destination
;
4313 snoop_addr
.sin_port
= ntohs(port
);
4315 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4316 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4317 htons(snoop_addr
.sin_port
));
4319 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4320 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4322 STAT(packets_snooped
);
4325 static int dump_session(FILE **f
, sessiont
*s
)
4327 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4332 char filename
[1024];
4334 time_t now
= time(NULL
);
4336 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4337 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4339 if (!(*f
= fopen(filename
, "w")))
4341 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4345 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4346 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4351 "# format: username ip qos uptxoctets downrxoctets\n",
4353 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4358 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4359 fprintf(*f
, "%s %s %d %u %u\n",
4360 s
->user
, // username
4361 fmtaddr(htonl(s
->ip
), 0), // ip
4362 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4363 (uint32_t) s
->cin_delta
, // uptxoctets
4364 (uint32_t) s
->cout_delta
); // downrxoctets
4366 s
->cin_delta
= s
->cout_delta
= 0;
4371 static void dump_acct_info(int all
)
4377 CSTAT(dump_acct_info
);
4381 for (i
= 0; i
< shut_acct_n
; i
++)
4382 dump_session(&f
, &shut_acct
[i
]);
4388 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4389 dump_session(&f
, &session
[i
]);
4396 int main(int argc
, char *argv
[])
4400 char *optconfig
= CONFIGFILE
;
4402 time(&basetime
); // start clock
4405 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4410 if (fork()) exit(0);
4412 freopen("/dev/null", "r", stdin
);
4413 freopen("/dev/null", "w", stdout
);
4414 freopen("/dev/null", "w", stderr
);
4423 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4426 printf("Args are:\n"
4427 "\t-d\t\tDetach from terminal\n"
4428 "\t-c <file>\tConfig file\n"
4429 "\t-h <hostname>\tForce hostname\n"
4437 // Start the timer routine off
4439 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4442 initdata(optdebug
, optconfig
);
4447 init_tbf(config
->num_tbfs
);
4449 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4450 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4451 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4454 rlim
.rlim_cur
= RLIM_INFINITY
;
4455 rlim
.rlim_max
= RLIM_INFINITY
;
4456 // Remove the maximum core size
4457 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4458 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4460 // Make core dumps go to /tmp
4464 if (config
->scheduler_fifo
)
4467 struct sched_param params
= {0};
4468 params
.sched_priority
= 1;
4470 if (get_nprocs() < 2)
4472 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4473 config
->scheduler_fifo
= 0;
4477 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4479 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4483 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4484 config
->scheduler_fifo
= 0;
4489 /* Set up the cluster communications port. */
4490 if (cluster_init() < 0)
4494 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4502 unsigned seed
= time_now
^ getpid();
4503 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4507 signal(SIGHUP
, sighup_handler
);
4508 signal(SIGCHLD
, sigchild_handler
);
4509 signal(SIGTERM
, shutdown_handler
);
4510 signal(SIGINT
, shutdown_handler
);
4511 signal(SIGQUIT
, shutdown_handler
);
4513 // Prevent us from getting paged out
4514 if (config
->lock_pages
)
4516 if (!mlockall(MCL_CURRENT
))
4517 LOG(1, 0, 0, "Locking pages into memory\n");
4519 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4524 /* remove plugins (so cleanup code gets run) */
4527 // Remove the PID file if we wrote it
4528 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4529 unlink(config
->pid_file
);
4531 /* kill CLI children */
4532 signal(SIGTERM
, SIG_IGN
);
4537 static void sighup_handler(int sig
)
4542 static void shutdown_handler(int sig
)
4544 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4547 static void sigchild_handler(int sig
)
4549 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4553 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4556 *challenge_response
= NULL
;
4558 if (!*config
->l2tp_secret
)
4560 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4564 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4566 *challenge_response
= calloc(17, 1);
4569 MD5_Update(&ctx
, &id
, 1);
4570 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4571 MD5_Update(&ctx
, challenge
, challenge_length
);
4572 MD5_Final(*challenge_response
, &ctx
);
4577 static int facility_value(char *name
)
4580 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4582 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4583 return facilitynames
[i
].c_val
;
4588 static void update_config()
4592 static int timeout
= 0;
4593 static int interval
= 0;
4600 if (log_stream
!= stderr
)
4606 if (*config
->log_filename
)
4608 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4610 char *p
= config
->log_filename
+ 7;
4613 openlog("l2tpns", LOG_PID
, facility_value(p
));
4617 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4619 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4621 fseek(log_stream
, 0, SEEK_END
);
4622 setbuf(log_stream
, NULL
);
4626 log_stream
= stderr
;
4627 setbuf(log_stream
, NULL
);
4633 log_stream
= stderr
;
4634 setbuf(log_stream
, NULL
);
4637 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4638 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4640 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4641 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4642 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4644 // reset MRU/MSS globals
4645 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4646 if (MRU
> PPPoE_MRU
)
4649 MSS
= MRU
- TCP_HDRS
;
4652 config
->numradiusservers
= 0;
4653 for (i
= 0; i
< MAXRADSERVER
; i
++)
4654 if (config
->radiusserver
[i
])
4656 config
->numradiusservers
++;
4657 // Set radius port: if not set, take the port from the
4658 // first radius server. For the first radius server,
4659 // take the #defined default value from l2tpns.h
4661 // test twice, In case someone works with
4662 // a secondary radius server without defining
4663 // a primary one, this will work even then.
4664 if (i
> 0 && !config
->radiusport
[i
])
4665 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4666 if (!config
->radiusport
[i
])
4667 config
->radiusport
[i
] = RADPORT
;
4670 if (!config
->numradiusservers
)
4671 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4673 // parse radius_authtypes_s
4674 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4675 p
= config
->radius_authtypes_s
;
4678 char *s
= strpbrk(p
, " \t,");
4684 while (*s
== ' ' || *s
== '\t')
4691 if (!strncasecmp("chap", p
, strlen(p
)))
4693 else if (!strncasecmp("pap", p
, strlen(p
)))
4696 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4698 config
->radius_authtypes
|= type
;
4699 if (!config
->radius_authprefer
)
4700 config
->radius_authprefer
= type
;
4705 if (!config
->radius_authtypes
)
4707 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4708 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4711 // normalise radius_authtypes_s
4712 if (config
->radius_authprefer
== AUTHPAP
)
4714 strcpy(config
->radius_authtypes_s
, "pap");
4715 if (config
->radius_authtypes
& AUTHCHAP
)
4716 strcat(config
->radius_authtypes_s
, ", chap");
4720 strcpy(config
->radius_authtypes_s
, "chap");
4721 if (config
->radius_authtypes
& AUTHPAP
)
4722 strcat(config
->radius_authtypes_s
, ", pap");
4725 if (!config
->radius_dae_port
)
4726 config
->radius_dae_port
= DAEPORT
;
4728 // re-initialise the random number source
4729 initrandom(config
->random_device
);
4732 for (i
= 0; i
< MAXPLUGINS
; i
++)
4734 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
4737 if (*config
->plugins
[i
])
4740 add_plugin(config
->plugins
[i
]);
4742 else if (*config
->old_plugins
[i
])
4745 remove_plugin(config
->old_plugins
[i
]);
4749 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
4750 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
4751 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
4752 if (!*config
->cluster_interface
)
4753 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
4755 if (!config
->cluster_hb_interval
)
4756 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
4758 if (!config
->cluster_hb_timeout
)
4759 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
4761 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
4763 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
4764 // late, ensure we're sufficiently larger than that
4765 int t
= 4 * config
->cluster_hb_interval
+ 11;
4767 if (config
->cluster_hb_timeout
< t
)
4769 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
4770 config
->cluster_hb_timeout
= t
;
4773 // Push timing changes to the slaves immediately if we're the master
4774 if (config
->cluster_iam_master
)
4775 cluster_heartbeat();
4777 interval
= config
->cluster_hb_interval
;
4778 timeout
= config
->cluster_hb_timeout
;
4782 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
4785 if ((f
= fopen(config
->pid_file
, "w")))
4787 fprintf(f
, "%d\n", getpid());
4789 config
->wrote_pid
= 1;
4793 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
4798 static void read_config_file()
4802 if (!config
->config_file
) return;
4803 if (!(f
= fopen(config
->config_file
, "r")))
4805 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
4809 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
4811 LOG(3, 0, 0, "Done reading config file\n");
4815 int sessionsetup(sessionidt s
, tunnelidt t
)
4817 // A session now exists, set it up
4823 CSTAT(sessionsetup
);
4825 LOG(3, s
, t
, "Doing session setup for session\n");
4829 assign_ip_address(s
);
4832 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
4833 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
4836 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
4837 fmtaddr(htonl(session
[s
].ip
), 0));
4841 // Make sure this is right
4842 session
[s
].tunnel
= t
;
4844 // Join a bundle if the MRRU option is accepted
4845 if (session
[s
].mrru
> 0 && !session
[s
].bundle
)
4847 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
4849 cluster_send_bundle(session
[s
].bundle
);
4852 // zap old sessions with same IP and/or username
4853 // Don't kill gardened sessions - doing so leads to a DoS
4854 // from someone who doesn't need to know the password
4857 user
= session
[s
].user
;
4858 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4860 if (i
== s
) continue;
4861 if (!session
[s
].opened
) continue;
4862 if (ip
== session
[i
].ip
)
4864 sessionkill(i
, "Duplicate IP address");
4868 if (config
->allow_duplicate_users
)
4871 if (session
[s
].walled_garden
|| session
[i
].walled_garden
)
4874 // Allow duplicate sessions for guest account.
4875 if (*config
->guest_user
&& !strcasecmp(user
, config
->guest_user
))
4878 // Allow duplicate sessions for multilink ones of the same bundle.
4879 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
4882 // Drop the new session in case of duplicate sessionss, not the old one.
4883 if (!strcasecmp(user
, session
[i
].user
))
4884 sessionkill(i
, "Duplicate session for users");
4891 // Add the route for this session.
4892 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
4894 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
4895 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
4898 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
4901 // Static IPs need to be routed if not already
4902 // convered by a Framed-Route. Anything else is part
4903 // of the IP address pool and is already routed, it
4904 // just needs to be added to the IP cache.
4905 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
4906 if (session
[s
].ip_pool_index
== -1) // static ip
4908 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
4911 cache_ipmap(session
[s
].ip
, s
);
4914 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
4915 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
4917 // Run the plugin's against this new session.
4919 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
4920 run_plugins(PLUGIN_NEW_SESSION
, &data
);
4923 // Allocate TBFs if throttled
4924 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
4925 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
4927 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
4929 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
4930 fmtaddr(htonl(session
[s
].ip
), 0),
4931 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
4933 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
4935 return 1; // RADIUS OK and IP allocated, done...
4939 // This session just got dropped on us by the master or something.
4940 // Make sure our tables up up to date...
4942 int load_session(sessionidt s
, sessiont
*new)
4948 if (new->ip_pool_index
>= MAXIPPOOL
||
4949 new->tunnel
>= MAXTUNNEL
)
4951 LOG(0, s
, 0, "Strange session update received!\n");
4952 // FIXME! What to do here?
4957 // Ok. All sanity checks passed. Now we're committed to
4958 // loading the new session.
4961 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
4963 // See if routes/ip cache need updating
4964 if (new->ip
!= session
[s
].ip
)
4967 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
4968 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
4969 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
4977 // remove old routes...
4978 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
4980 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
4981 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
4984 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
4990 if (session
[s
].ip_pool_index
== -1) // static IP
4992 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
4994 else // It's part of the IP pool, remove it manually.
4995 uncache_ipmap(session
[s
].ip
);
5000 // add new routes...
5001 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5003 if ((new->ip
& new->route
[i
].mask
) ==
5004 (new->route
[i
].ip
& new->route
[i
].mask
))
5007 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
5013 // If there's a new one, add it.
5014 if (new->ip_pool_index
== -1)
5016 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5019 cache_ipmap(new->ip
, s
);
5024 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5025 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5028 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5030 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5034 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5036 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5037 new->filter_out
= 0;
5040 if (new->filter_in
!= session
[s
].filter_in
)
5042 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5043 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5046 if (new->filter_out
!= session
[s
].filter_out
)
5048 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5049 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5052 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5053 // for walking the sessions to forward byte counts to the master.
5054 config
->cluster_highest_sessionid
= s
;
5056 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5058 // Do fixups into address pool.
5059 if (new->ip_pool_index
!= -1)
5060 fix_address_pool(s
);
5065 static void initplugins()
5069 loaded_plugins
= ll_init();
5070 // Initialize the plugins to nothing
5071 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5072 plugins
[i
] = ll_init();
5075 static void *open_plugin(char *plugin_name
, int load
)
5077 char path
[256] = "";
5079 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5080 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5081 return dlopen(path
, RTLD_NOW
);
5084 // plugin callback to get a config value
5085 static void *getconfig(char *key
, enum config_typet type
)
5089 for (i
= 0; config_values
[i
].key
; i
++)
5091 if (!strcmp(config_values
[i
].key
, key
))
5093 if (config_values
[i
].type
== type
)
5094 return ((void *) config
) + config_values
[i
].offset
;
5096 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5097 key
, type
, config_values
[i
].type
);
5103 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5107 static int add_plugin(char *plugin_name
)
5109 static struct pluginfuncs funcs
= {
5114 sessiontbysessionidt
,
5115 sessionidtbysessiont
,
5122 cluster_send_session
,
5125 void *p
= open_plugin(plugin_name
, 1);
5126 int (*initfunc
)(struct pluginfuncs
*);
5131 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5135 if (ll_contains(loaded_plugins
, p
))
5138 return 0; // already loaded
5142 int *v
= dlsym(p
, "plugin_api_version");
5143 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5145 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5151 if ((initfunc
= dlsym(p
, "plugin_init")))
5153 if (!initfunc(&funcs
))
5155 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5161 ll_push(loaded_plugins
, p
);
5163 for (i
= 0; i
< max_plugin_functions
; i
++)
5166 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5168 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5169 ll_push(plugins
[i
], x
);
5173 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5177 static void run_plugin_done(void *plugin
)
5179 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5185 static int remove_plugin(char *plugin_name
)
5187 void *p
= open_plugin(plugin_name
, 0);
5193 if (ll_contains(loaded_plugins
, p
))
5196 for (i
= 0; i
< max_plugin_functions
; i
++)
5199 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5200 ll_delete(plugins
[i
], x
);
5203 ll_delete(loaded_plugins
, p
);
5209 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5213 int run_plugins(int plugin_type
, void *data
)
5215 int (*func
)(void *data
);
5217 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5218 return PLUGIN_RET_ERROR
;
5220 ll_reset(plugins
[plugin_type
]);
5221 while ((func
= ll_next(plugins
[plugin_type
])))
5225 if (r
!= PLUGIN_RET_OK
)
5226 return r
; // stop here
5229 return PLUGIN_RET_OK
;
5232 static void plugins_done()
5236 ll_reset(loaded_plugins
);
5237 while ((p
= ll_next(loaded_plugins
)))
5241 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5243 struct nsctl request
;
5244 struct nsctl response
;
5245 int type
= unpack_control(&request
, buf
, len
);
5249 if (log_stream
&& config
->debug
>= 4)
5253 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5254 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5258 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5259 dump_control(&request
, log_stream
);
5265 case NSCTL_REQ_LOAD
:
5266 if (request
.argc
!= 1)
5268 response
.type
= NSCTL_RES_ERR
;
5270 response
.argv
[0] = "name of plugin required";
5272 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5274 response
.type
= NSCTL_RES_ERR
;
5276 response
.argv
[0] = !r
5277 ? "plugin already loaded"
5278 : "error loading plugin";
5282 response
.type
= NSCTL_RES_OK
;
5288 case NSCTL_REQ_UNLOAD
:
5289 if (request
.argc
!= 1)
5291 response
.type
= NSCTL_RES_ERR
;
5293 response
.argv
[0] = "name of plugin required";
5295 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5297 response
.type
= NSCTL_RES_ERR
;
5299 response
.argv
[0] = !r
5300 ? "plugin not loaded"
5301 : "plugin not found";
5305 response
.type
= NSCTL_RES_OK
;
5311 case NSCTL_REQ_HELP
:
5312 response
.type
= NSCTL_RES_OK
;
5315 ll_reset(loaded_plugins
);
5316 while ((p
= ll_next(loaded_plugins
)))
5318 char **help
= dlsym(p
, "plugin_control_help");
5319 while (response
.argc
< 0xff && help
&& *help
)
5320 response
.argv
[response
.argc
++] = *help
++;
5325 case NSCTL_REQ_CONTROL
:
5327 struct param_control param
= {
5328 config
->cluster_iam_master
,
5335 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5337 if (r
== PLUGIN_RET_ERROR
)
5339 response
.type
= NSCTL_RES_ERR
;
5341 response
.argv
[0] = param
.additional
5343 : "error returned by plugin";
5345 else if (r
== PLUGIN_RET_NOTMASTER
)
5347 static char msg
[] = "must be run on master: 000.000.000.000";
5349 response
.type
= NSCTL_RES_ERR
;
5351 if (config
->cluster_master_address
)
5353 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5354 response
.argv
[0] = msg
;
5358 response
.argv
[0] = "must be run on master: none elected";
5361 else if (!(param
.response
& NSCTL_RESPONSE
))
5363 response
.type
= NSCTL_RES_ERR
;
5365 response
.argv
[0] = param
.response
5366 ? "unrecognised response value from plugin"
5367 : "unhandled action";
5371 response
.type
= param
.response
;
5373 if (param
.additional
)
5376 response
.argv
[0] = param
.additional
;
5384 response
.type
= NSCTL_RES_ERR
;
5386 response
.argv
[0] = "error unpacking control packet";
5389 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5392 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5396 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5399 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5400 if (log_stream
&& config
->debug
>= 4)
5402 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5403 dump_control(&response
, log_stream
);
5407 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5408 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5413 static tunnelidt
new_tunnel()
5416 for (i
= 1; i
< MAXTUNNEL
; i
++)
5418 if (tunnel
[i
].state
== TUNNELFREE
)
5420 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5421 if (i
> config
->cluster_highest_tunnelid
)
5422 config
->cluster_highest_tunnelid
= i
;
5426 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5431 // We're becoming the master. Do any required setup..
5433 // This is principally telling all the plugins that we're
5434 // now a master, and telling them about all the sessions
5435 // that are active too..
5437 void become_master(void)
5440 static struct event_data d
[RADIUS_FDS
];
5441 struct epoll_event e
;
5443 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5445 // running a bunch of iptables commands is slow and can cause
5446 // the master to drop tunnels on takeover--kludge around the
5447 // problem by forking for the moment (note: race)
5448 if (!fork_and_close())
5450 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5452 if (!session
[s
].opened
) // Not an in-use session.
5455 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5462 for (i
= 0; i
< RADIUS_FDS
; i
++)
5464 d
[i
].type
= FD_TYPE_RADIUS
;
5468 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5472 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5478 if (CLI_HELP_REQUESTED
)
5479 return CLI_HELP_NO_ARGS
;
5482 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5484 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5487 if (!session
[s
].opened
)
5490 idle
= time_now
- session
[s
].last_data
;
5491 idle
/= 5 ; // In multiples of 5 seconds.
5501 for (i
= 0; i
< 63; ++i
)
5503 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5505 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5506 cli_print(cli
, "%d total sessions open.", count
);
5510 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5516 if (CLI_HELP_REQUESTED
)
5517 return CLI_HELP_NO_ARGS
;
5520 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5522 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5525 if (!session
[s
].opened
)
5528 d
= time_now
- session
[s
].opened
;
5531 while (d
> 1 && open
< 32)
5541 for (i
= 0; i
< 30; ++i
)
5543 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5546 cli_print(cli
, "%d total sessions open.", count
);
5552 * This unencodes the AVP using the L2TP secret and the previously
5553 * stored random vector. It overwrites the hidden data with the
5554 * unhidden AVP subformat.
5556 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5562 uint16_t m
= htons(type
);
5564 // Compute initial pad
5566 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5567 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5568 MD5_Update(&ctx
, vector
, vec_len
);
5569 MD5_Final(digest
, &ctx
);
5571 // pointer to last decoded 16 octets
5576 // calculate a new pad based on the last decoded block
5577 if (d
>= sizeof(digest
))
5580 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5581 MD5_Update(&ctx
, last
, sizeof(digest
));
5582 MD5_Final(digest
, &ctx
);
5588 *value
++ ^= digest
[d
++];
5593 int find_filter(char const *name
, size_t len
)
5598 for (i
= 0; i
< MAXFILTER
; i
++)
5600 if (!*ip_filters
[i
].name
)
5608 if (strlen(ip_filters
[i
].name
) != len
)
5611 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5618 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5622 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5623 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5624 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5625 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5626 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5632 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5636 case FILTER_FLAG_OP_ANY
:
5637 return (flags
& sflags
) || (~flags
& cflags
);
5639 case FILTER_FLAG_OP_ALL
:
5640 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5642 case FILTER_FLAG_OP_EST
:
5643 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5649 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5651 uint16_t frag_offset
;
5655 uint16_t src_port
= 0;
5656 uint16_t dst_port
= 0;
5658 ip_filter_rulet
*rule
;
5660 if (len
< 20) // up to end of destination address
5663 if ((*buf
>> 4) != 4) // IPv4
5666 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5668 src_ip
= *(in_addr_t
*) (buf
+ 12);
5669 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5671 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5673 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5674 if (len
< l
+ 4) // ports
5677 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
5678 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
5679 if (proto
== IPPROTO_TCP
)
5681 if (len
< l
+ 14) // flags
5684 flags
= buf
[l
+ 13] & 0x3f;
5688 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
5690 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
5693 if (rule
->src_wild
!= INADDR_BROADCAST
&&
5694 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
5697 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
5698 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
5703 // layer 4 deny rules are skipped
5704 if (rule
->action
== FILTER_ACTION_DENY
&&
5705 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
5713 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
5715 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
5718 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
5721 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
5722 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
5729 return rule
->action
== FILTER_ACTION_PERMIT
;