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.172 2006/12/18 12:05:36 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");
3057 if (sess_local
[s
].lcp
.restart
<= time_now
)
3059 int next_state
= session
[s
].ppp
.lcp
;
3060 switch (session
[s
].ppp
.lcp
)
3064 next_state
= RequestSent
;
3067 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3069 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3070 sendlcp(s
, session
[s
].tunnel
);
3071 change_state(s
, lcp
, next_state
);
3075 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3076 STAT(session_timeout
);
3086 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3088 int next_state
= session
[s
].ppp
.ipcp
;
3089 switch (session
[s
].ppp
.ipcp
)
3093 next_state
= RequestSent
;
3096 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3098 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3099 sendipcp(s
, session
[s
].tunnel
);
3100 change_state(s
, ipcp
, next_state
);
3104 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3105 STAT(session_timeout
);
3115 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3117 int next_state
= session
[s
].ppp
.ipv6cp
;
3118 switch (session
[s
].ppp
.ipv6cp
)
3122 next_state
= RequestSent
;
3125 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3127 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3128 sendipv6cp(s
, session
[s
].tunnel
);
3129 change_state(s
, ipv6cp
, next_state
);
3133 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3134 change_state(s
, ipv6cp
, Stopped
);
3141 if (sess_local
[s
].ccp
.restart
<= time_now
)
3143 int next_state
= session
[s
].ppp
.ccp
;
3144 switch (session
[s
].ppp
.ccp
)
3148 next_state
= RequestSent
;
3151 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3153 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3154 sendccp(s
, session
[s
].tunnel
);
3155 change_state(s
, ccp
, next_state
);
3159 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3160 change_state(s
, ccp
, Stopped
);
3167 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3168 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3170 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3171 STAT(session_timeout
);
3176 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3177 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3178 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3180 uint8_t b
[MAXETHER
];
3182 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3186 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3187 *(uint16_t *)(q
+ 2) = htons(8); // Length
3188 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3190 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3191 (int)(time_now
- session
[s
].last_packet
));
3192 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3193 sess_local
[s
].last_echo
= time_now
;
3197 // Drop sessions who have reached session_timeout seconds
3198 if (session
[s
].session_timeout
)
3200 bundleidt bid
= session
[s
].bundle
;
3203 if (time_now
- bundle
[bid
].last_check
>= 1)
3205 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3206 bundle
[bid
].last_check
= time_now
;
3207 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3210 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3212 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3219 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3221 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3227 // Drop sessions who have reached idle_timeout seconds
3228 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3230 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3231 STAT(session_timeout
);
3236 // Check for actions requested from the CLI
3237 if ((a
= cli_session_actions
[s
].action
))
3241 cli_session_actions
[s
].action
= 0;
3242 if (a
& CLI_SESS_KILL
)
3244 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3245 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3246 a
= 0; // dead, no need to check for other actions
3250 if (a
& CLI_SESS_NOSNOOP
)
3252 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3253 session
[s
].snoop_ip
= 0;
3254 session
[s
].snoop_port
= 0;
3258 else if (a
& CLI_SESS_SNOOP
)
3260 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3261 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3262 cli_session_actions
[s
].snoop_port
);
3264 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3265 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3270 if (a
& CLI_SESS_NOTHROTTLE
)
3272 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3273 throttle_session(s
, 0, 0);
3277 else if (a
& CLI_SESS_THROTTLE
)
3279 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3280 cli_session_actions
[s
].throttle_in
,
3281 cli_session_actions
[s
].throttle_out
);
3283 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3288 if (a
& CLI_SESS_NOFILTER
)
3290 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3291 filter_session(s
, 0, 0);
3295 else if (a
& CLI_SESS_FILTER
)
3297 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3298 cli_session_actions
[s
].filter_in
,
3299 cli_session_actions
[s
].filter_out
);
3301 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3307 cluster_send_session(s
);
3310 // RADIUS interim accounting
3311 if (config
->radius_accounting
&& config
->radius_interim
> 0
3312 && session
[s
].ip
&& !session
[s
].walled_garden
3313 && !sess_local
[s
].radius
// RADIUS already in progress
3314 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3315 && session
[s
].flags
& SESSION_STARTED
)
3317 int rad
= radiusnew(s
);
3320 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3321 STAT(radius_overflow
);
3325 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3326 session
[s
].user
, session
[s
].unique_id
);
3328 radiussend(rad
, RADIUSINTERIM
);
3329 sess_local
[s
].last_interim
= time_now
;
3334 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3335 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3339 // Are we in the middle of a tunnel update, or radius
3342 static int still_busy(void)
3345 static clockt last_talked
= 0;
3346 static clockt start_busy_wait
= 0;
3348 if (!config
->cluster_iam_master
)
3351 static time_t stopped_bgp
= 0;
3356 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3358 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3359 if (bgp_peers
[i
].state
== Established
)
3360 bgp_stop(&bgp_peers
[i
]);
3362 stopped_bgp
= time_now
;
3364 // we don't want to become master
3365 cluster_send_ping(0);
3370 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
3378 if (main_quit
== QUIT_SHUTDOWN
)
3380 static int dropped
= 0;
3385 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3386 for (i
= 1; i
< MAXTUNNEL
; i
++)
3387 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3388 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3394 if (start_busy_wait
== 0)
3395 start_busy_wait
= TIME
;
3397 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3399 if (!tunnel
[i
].controlc
)
3402 if (last_talked
!= TIME
)
3404 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3410 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3411 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3413 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3417 for (i
= 1; i
< MAXRADIUS
; i
++)
3419 if (radius
[i
].state
== RADIUSNULL
)
3421 if (radius
[i
].state
== RADIUSWAIT
)
3424 if (last_talked
!= TIME
)
3426 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3436 # include <sys/epoll.h>
3438 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3439 # include "fake_epoll.h"
3442 // the base set of fds polled: cli, cluster, tun, udp, control, dae
3445 // additional polled fds
3447 # define EXTRA_FDS BGP_NUM_PEERS
3449 # define EXTRA_FDS 0
3452 // main loop - gets packets on tun or udp and processes them
3453 static void mainloop(void)
3457 clockt next_cluster_ping
= 0; // send initial ping immediately
3458 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3459 int maxevent
= sizeof(events
)/sizeof(*events
);
3461 if ((epollfd
= epoll_create(maxevent
)) < 0)
3463 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3467 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d\n",
3468 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
);
3470 /* setup our fds to poll for input */
3472 static struct event_data d
[BASE_FDS
];
3473 struct epoll_event e
;
3480 d
[i
].type
= FD_TYPE_CLI
;
3481 e
.data
.ptr
= &d
[i
++];
3482 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3485 d
[i
].type
= FD_TYPE_CLUSTER
;
3486 e
.data
.ptr
= &d
[i
++];
3487 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3489 d
[i
].type
= FD_TYPE_TUN
;
3490 e
.data
.ptr
= &d
[i
++];
3491 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3493 d
[i
].type
= FD_TYPE_UDP
;
3494 e
.data
.ptr
= &d
[i
++];
3495 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3497 d
[i
].type
= FD_TYPE_CONTROL
;
3498 e
.data
.ptr
= &d
[i
++];
3499 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3501 d
[i
].type
= FD_TYPE_DAE
;
3502 e
.data
.ptr
= &d
[i
++];
3503 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3507 signal(SIGPIPE
, SIG_IGN
);
3508 bgp_setup(config
->as_number
);
3509 if (config
->bind_address
)
3510 bgp_add_route(config
->bind_address
, 0xffffffff);
3512 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3514 if (config
->neighbour
[i
].name
[0])
3515 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3516 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3517 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3521 while (!main_quit
|| still_busy())
3531 config
->reload_config
++;
3534 if (config
->reload_config
)
3536 config
->reload_config
= 0;
3544 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3545 STAT(select_called
);
3550 if (errno
== EINTR
||
3551 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3554 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3560 struct sockaddr_in addr
;
3561 struct in_addr local
;
3566 int cluster_ready
= 0;
3569 int cluster_pkts
= 0;
3571 uint32_t bgp_events
[BGP_NUM_PEERS
];
3572 memset(bgp_events
, 0, sizeof(bgp_events
));
3575 for (c
= n
, i
= 0; i
< c
; i
++)
3577 struct event_data
*d
= events
[i
].data
.ptr
;
3581 case FD_TYPE_CLI
: // CLI connections
3585 alen
= sizeof(addr
);
3586 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3592 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3598 // these are handled below, with multiple interleaved reads
3599 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3600 case FD_TYPE_TUN
: tun_ready
++; break;
3601 case FD_TYPE_UDP
: udp_ready
++; break;
3603 case FD_TYPE_CONTROL
: // nsctl commands
3604 alen
= sizeof(addr
);
3605 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3606 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3610 case FD_TYPE_DAE
: // DAE requests
3611 alen
= sizeof(addr
);
3612 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3613 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3617 case FD_TYPE_RADIUS
: // RADIUS response
3618 alen
= sizeof(addr
);
3619 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3620 if (s
>= 0 && config
->cluster_iam_master
)
3622 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3623 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3624 processrad(buf
, s
, d
->index
);
3626 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3627 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3635 bgp_events
[d
->index
] = events
[i
].events
;
3641 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3646 bgp_process(bgp_events
);
3649 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3654 alen
= sizeof(addr
);
3655 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3657 processudp(buf
, s
, &addr
);
3670 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3685 alen
= sizeof(addr
);
3686 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3688 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3699 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3700 STAT(multi_read_used
);
3702 if (c
>= config
->multi_read_count
)
3704 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3705 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3707 STAT(multi_read_exceeded
);
3714 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
3716 // Log current traffic stats
3717 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3718 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3719 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
3720 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
3721 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
3723 udp_tx
= udp_rx
= 0;
3724 udp_rx_pkt
= eth_rx_pkt
= 0;
3725 eth_tx
= eth_rx
= 0;
3728 if (config
->dump_speed
)
3729 printf("%s\n", config
->bandwidth
);
3731 // Update the internal time counter
3732 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3736 struct param_timer p
= { time_now
};
3737 run_plugins(PLUGIN_TIMER
, &p
);
3741 // Runs on every machine (master and slaves).
3742 if (next_cluster_ping
<= TIME
)
3744 // Check to see which of the cluster is still alive..
3746 cluster_send_ping(basetime
); // Only does anything if we're a slave
3747 cluster_check_master(); // ditto.
3749 cluster_heartbeat(); // Only does anything if we're a master.
3750 cluster_check_slaves(); // ditto.
3752 master_update_counts(); // If we're a slave, send our byte counters to our master.
3754 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
3755 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
3757 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
3760 if (!config
->cluster_iam_master
)
3763 // Run token bucket filtering queue..
3764 // Only run it every 1/10th of a second.
3766 static clockt last_run
= 0;
3767 if (last_run
!= TIME
)
3774 // Handle timeouts, retries etc.
3776 static double last_clean
= 0;
3780 TIME
= now(&this_clean
);
3781 diff
= this_clean
- last_clean
;
3783 // Run during idle time (after we've handled
3784 // all incoming packets) or every 1/10th sec
3785 if (!more
|| diff
> 0.1)
3787 regular_cleanups(diff
);
3788 last_clean
= this_clean
;
3792 if (*config
->accounting_dir
)
3794 static clockt next_acct
= 0;
3795 static clockt next_shut_acct
= 0;
3797 if (next_acct
<= TIME
)
3799 // Dump accounting data
3800 next_acct
= TIME
+ ACCT_TIME
;
3801 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3804 else if (next_shut_acct
<= TIME
)
3806 // Dump accounting data for shutdown sessions
3807 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3814 // Are we the master and shutting down??
3815 if (config
->cluster_iam_master
)
3816 cluster_heartbeat(); // Flush any queued changes..
3818 // Ok. Notify everyone we're shutting down. If we're
3819 // the master, this will force an election.
3820 cluster_send_ping(0);
3823 // Important!!! We MUST not process any packets past this point!
3824 LOG(1, 0, 0, "Shutdown complete\n");
3827 static void stripdomain(char *host
)
3831 if ((p
= strchr(host
, '.')))
3837 FILE *resolv
= fopen("/etc/resolv.conf", "r");
3843 while (fgets(buf
, sizeof(buf
), resolv
))
3845 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
3848 if (!isspace(buf
[6]))
3852 while (isspace(*b
)) b
++;
3857 while (*b
&& !isspace(*b
)) b
++;
3859 if (buf
[0] == 'd') // domain is canonical
3865 // first search line
3868 // hold, may be subsequent domain line
3869 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
3880 int hl
= strlen(host
);
3881 int dl
= strlen(domain
);
3882 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
3883 host
[hl
-dl
- 1] = 0;
3887 *p
= 0; // everything after first dot
3892 // Init data structures
3893 static void initdata(int optdebug
, char *optconfig
)
3897 if (!(config
= shared_malloc(sizeof(configt
))))
3899 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
3903 memset(config
, 0, sizeof(configt
));
3904 time(&config
->start_time
);
3905 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
3906 config
->debug
= optdebug
;
3907 config
->num_tbfs
= MAXTBFS
;
3908 config
->rl_rate
= 28; // 28kbps
3909 config
->cluster_mcast_ttl
= 1;
3910 config
->cluster_master_min_adv
= 1;
3911 config
->ppp_restart_time
= 3;
3912 config
->ppp_max_configure
= 10;
3913 config
->ppp_max_failure
= 5;
3914 strcpy(config
->random_device
, RANDOMDEVICE
);
3916 log_stream
= stderr
;
3919 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
3921 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
3924 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
3927 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
3929 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
3932 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
3934 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
3937 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
3939 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
3942 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
3944 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
3947 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
3949 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
3953 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
3955 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
3959 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
3961 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
3965 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
3967 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
3971 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
3973 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
3976 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
3978 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
3980 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
3983 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
3985 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
3987 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
3990 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
3992 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
3993 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
3994 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
3995 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
3996 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
3998 // Put all the sessions on the free list marked as undefined.
3999 for (i
= 1; i
< MAXSESSION
; i
++)
4001 session
[i
].next
= i
+ 1;
4002 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4004 session
[MAXSESSION
- 1].next
= 0;
4007 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4008 for (i
= 1; i
< MAXTUNNEL
; i
++)
4009 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4011 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4012 bundle
[i
].state
= BUNDLEUNDEF
;
4017 // Grab my hostname unless it's been specified
4018 gethostname(hostname
, sizeof(hostname
));
4019 stripdomain(hostname
);
4022 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4025 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4027 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4033 static int assign_ip_address(sessionidt s
)
4037 time_t best_time
= time_now
;
4038 char *u
= session
[s
].user
;
4042 CSTAT(assign_ip_address
);
4044 for (i
= 1; i
< ip_pool_size
; i
++)
4046 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4049 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4056 if (ip_address_pool
[i
].last
< best_time
)
4059 if (!(best_time
= ip_address_pool
[i
].last
))
4060 break; // never used, grab this one
4066 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4070 session
[s
].ip
= ip_address_pool
[best
].address
;
4071 session
[s
].ip_pool_index
= best
;
4072 ip_address_pool
[best
].assigned
= 1;
4073 ip_address_pool
[best
].last
= time_now
;
4074 ip_address_pool
[best
].session
= s
;
4075 if (session
[s
].walled_garden
)
4076 /* Don't track addresses of users in walled garden (note: this
4077 means that their address isn't "sticky" even if they get
4079 ip_address_pool
[best
].user
[0] = 0;
4081 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4084 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4085 reuse
? "Reusing" : "Allocating", best
);
4090 static void free_ip_address(sessionidt s
)
4092 int i
= session
[s
].ip_pool_index
;
4095 CSTAT(free_ip_address
);
4098 return; // what the?
4100 if (i
< 0) // Is this actually part of the ip pool?
4104 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4106 ip_address_pool
[i
].assigned
= 0;
4107 ip_address_pool
[i
].session
= 0;
4108 ip_address_pool
[i
].last
= time_now
;
4112 // Fsck the address pool against the session table.
4113 // Normally only called when we become a master.
4115 // This isn't perfect: We aren't keep tracking of which
4116 // users used to have an IP address.
4118 void rebuild_address_pool(void)
4123 // Zero the IP pool allocation, and build
4124 // a map from IP address to pool index.
4125 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4127 ip_address_pool
[i
].assigned
= 0;
4128 ip_address_pool
[i
].session
= 0;
4129 if (!ip_address_pool
[i
].address
)
4132 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4135 for (i
= 0; i
< MAXSESSION
; ++i
)
4138 if (!(session
[i
].opened
&& session
[i
].ip
))
4141 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4143 if (session
[i
].ip_pool_index
< 0)
4145 // Not allocated out of the pool.
4146 if (ipid
< 1) // Not found in the pool either? good.
4149 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4150 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4152 // Fall through and process it as part of the pool.
4156 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4158 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4160 session
[i
].ip_pool_index
= ipid
;
4164 ip_address_pool
[ipid
].assigned
= 1;
4165 ip_address_pool
[ipid
].session
= i
;
4166 ip_address_pool
[ipid
].last
= time_now
;
4167 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4168 session
[i
].ip_pool_index
= ipid
;
4169 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4174 // Fix the address pool to match a changed session.
4175 // (usually when the master sends us an update).
4176 static void fix_address_pool(int sid
)
4180 ipid
= session
[sid
].ip_pool_index
;
4182 if (ipid
> ip_pool_size
)
4183 return; // Ignore it. rebuild_address_pool will fix it up.
4185 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4186 return; // Just ignore it. rebuild_address_pool will take care of it.
4188 ip_address_pool
[ipid
].assigned
= 1;
4189 ip_address_pool
[ipid
].session
= sid
;
4190 ip_address_pool
[ipid
].last
= time_now
;
4191 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4195 // Add a block of addresses to the IP pool to hand out.
4197 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
4201 mask
= 0xffffffff; // Host route only.
4205 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4208 for (i
= addr
;(i
& mask
) == addr
; ++i
)
4210 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4211 continue; // Skip 0 and broadcast addresses.
4213 ip_address_pool
[ip_pool_size
].address
= i
;
4214 ip_address_pool
[ip_pool_size
].assigned
= 0;
4216 if (ip_pool_size
>= MAXIPPOOL
)
4218 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4224 // Initialize the IP address pool
4225 static void initippool()
4230 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4232 if (!(f
= fopen(IPPOOLFILE
, "r")))
4234 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4238 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4241 buf
[4095] = 0; // Force it to be zero terminated/
4243 if (*buf
== '#' || *buf
== '\n')
4244 continue; // Skip comments / blank lines
4245 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4246 if ((p
= (char *)strchr(buf
, ':')))
4250 src
= inet_addr(buf
);
4251 if (src
== INADDR_NONE
)
4253 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4256 // This entry is for a specific IP only
4257 if (src
!= config
->bind_address
)
4262 if ((p
= (char *)strchr(pool
, '/')))
4266 in_addr_t start
= 0, mask
= 0;
4268 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4270 if (!*p
|| !(numbits
= atoi(p
)))
4272 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4275 start
= ntohl(inet_addr(pool
));
4276 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
4278 // Add a static route for this pool
4279 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
4280 fmtaddr(htonl(start
), 0), 32 + mask
);
4282 routeset(0, start
, mask
, 0, 1);
4284 add_to_ip_pool(start
, mask
);
4288 // It's a single ip address
4289 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4293 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4296 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4298 struct sockaddr_in snoop_addr
= {0};
4299 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4302 snoop_addr
.sin_family
= AF_INET
;
4303 snoop_addr
.sin_addr
.s_addr
= destination
;
4304 snoop_addr
.sin_port
= ntohs(port
);
4306 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4307 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4308 htons(snoop_addr
.sin_port
));
4310 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4311 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4313 STAT(packets_snooped
);
4316 static int dump_session(FILE **f
, sessiont
*s
)
4318 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4323 char filename
[1024];
4325 time_t now
= time(NULL
);
4327 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4328 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4330 if (!(*f
= fopen(filename
, "w")))
4332 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4336 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4337 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4342 "# format: username ip qos uptxoctets downrxoctets\n",
4344 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4349 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4350 fprintf(*f
, "%s %s %d %u %u\n",
4351 s
->user
, // username
4352 fmtaddr(htonl(s
->ip
), 0), // ip
4353 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4354 (uint32_t) s
->cin_delta
, // uptxoctets
4355 (uint32_t) s
->cout_delta
); // downrxoctets
4357 s
->cin_delta
= s
->cout_delta
= 0;
4362 static void dump_acct_info(int all
)
4368 CSTAT(dump_acct_info
);
4372 for (i
= 0; i
< shut_acct_n
; i
++)
4373 dump_session(&f
, &shut_acct
[i
]);
4379 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4380 dump_session(&f
, &session
[i
]);
4387 int main(int argc
, char *argv
[])
4391 char *optconfig
= CONFIGFILE
;
4393 time(&basetime
); // start clock
4396 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4401 if (fork()) exit(0);
4403 freopen("/dev/null", "r", stdin
);
4404 freopen("/dev/null", "w", stdout
);
4405 freopen("/dev/null", "w", stderr
);
4414 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4417 printf("Args are:\n"
4418 "\t-d\t\tDetach from terminal\n"
4419 "\t-c <file>\tConfig file\n"
4420 "\t-h <hostname>\tForce hostname\n"
4428 // Start the timer routine off
4430 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4433 initdata(optdebug
, optconfig
);
4438 init_tbf(config
->num_tbfs
);
4440 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4441 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4442 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4445 rlim
.rlim_cur
= RLIM_INFINITY
;
4446 rlim
.rlim_max
= RLIM_INFINITY
;
4447 // Remove the maximum core size
4448 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4449 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4451 // Make core dumps go to /tmp
4455 if (config
->scheduler_fifo
)
4458 struct sched_param params
= {0};
4459 params
.sched_priority
= 1;
4461 if (get_nprocs() < 2)
4463 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4464 config
->scheduler_fifo
= 0;
4468 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4470 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4474 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4475 config
->scheduler_fifo
= 0;
4480 /* Set up the cluster communications port. */
4481 if (cluster_init() < 0)
4485 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4493 unsigned seed
= time_now
^ getpid();
4494 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4498 signal(SIGHUP
, sighup_handler
);
4499 signal(SIGCHLD
, sigchild_handler
);
4500 signal(SIGTERM
, shutdown_handler
);
4501 signal(SIGINT
, shutdown_handler
);
4502 signal(SIGQUIT
, shutdown_handler
);
4504 // Prevent us from getting paged out
4505 if (config
->lock_pages
)
4507 if (!mlockall(MCL_CURRENT
))
4508 LOG(1, 0, 0, "Locking pages into memory\n");
4510 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4515 /* remove plugins (so cleanup code gets run) */
4518 // Remove the PID file if we wrote it
4519 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4520 unlink(config
->pid_file
);
4522 /* kill CLI children */
4523 signal(SIGTERM
, SIG_IGN
);
4528 static void sighup_handler(int sig
)
4533 static void shutdown_handler(int sig
)
4535 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4538 static void sigchild_handler(int sig
)
4540 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4544 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4547 *challenge_response
= NULL
;
4549 if (!*config
->l2tp_secret
)
4551 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4555 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4557 *challenge_response
= calloc(17, 1);
4560 MD5_Update(&ctx
, &id
, 1);
4561 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4562 MD5_Update(&ctx
, challenge
, challenge_length
);
4563 MD5_Final(*challenge_response
, &ctx
);
4568 static int facility_value(char *name
)
4571 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4573 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4574 return facilitynames
[i
].c_val
;
4579 static void update_config()
4583 static int timeout
= 0;
4584 static int interval
= 0;
4591 if (log_stream
!= stderr
)
4597 if (*config
->log_filename
)
4599 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4601 char *p
= config
->log_filename
+ 7;
4604 openlog("l2tpns", LOG_PID
, facility_value(p
));
4608 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4610 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4612 fseek(log_stream
, 0, SEEK_END
);
4613 setbuf(log_stream
, NULL
);
4617 log_stream
= stderr
;
4618 setbuf(log_stream
, NULL
);
4624 log_stream
= stderr
;
4625 setbuf(log_stream
, NULL
);
4628 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4629 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4631 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4632 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4633 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4635 // reset MRU/MSS globals
4636 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4637 if (MRU
> PPPoE_MRU
)
4640 MSS
= MRU
- TCP_HDRS
;
4643 config
->numradiusservers
= 0;
4644 for (i
= 0; i
< MAXRADSERVER
; i
++)
4645 if (config
->radiusserver
[i
])
4647 config
->numradiusservers
++;
4648 // Set radius port: if not set, take the port from the
4649 // first radius server. For the first radius server,
4650 // take the #defined default value from l2tpns.h
4652 // test twice, In case someone works with
4653 // a secondary radius server without defining
4654 // a primary one, this will work even then.
4655 if (i
> 0 && !config
->radiusport
[i
])
4656 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4657 if (!config
->radiusport
[i
])
4658 config
->radiusport
[i
] = RADPORT
;
4661 if (!config
->numradiusservers
)
4662 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4664 // parse radius_authtypes_s
4665 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4666 p
= config
->radius_authtypes_s
;
4669 char *s
= strpbrk(p
, " \t,");
4675 while (*s
== ' ' || *s
== '\t')
4682 if (!strncasecmp("chap", p
, strlen(p
)))
4684 else if (!strncasecmp("pap", p
, strlen(p
)))
4687 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4689 config
->radius_authtypes
|= type
;
4690 if (!config
->radius_authprefer
)
4691 config
->radius_authprefer
= type
;
4696 if (!config
->radius_authtypes
)
4698 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4699 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4702 // normalise radius_authtypes_s
4703 if (config
->radius_authprefer
== AUTHPAP
)
4705 strcpy(config
->radius_authtypes_s
, "pap");
4706 if (config
->radius_authtypes
& AUTHCHAP
)
4707 strcat(config
->radius_authtypes_s
, ", chap");
4711 strcpy(config
->radius_authtypes_s
, "chap");
4712 if (config
->radius_authtypes
& AUTHPAP
)
4713 strcat(config
->radius_authtypes_s
, ", pap");
4716 if (!config
->radius_dae_port
)
4717 config
->radius_dae_port
= DAEPORT
;
4719 // re-initialise the random number source
4720 initrandom(config
->random_device
);
4723 for (i
= 0; i
< MAXPLUGINS
; i
++)
4725 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
4728 if (*config
->plugins
[i
])
4731 add_plugin(config
->plugins
[i
]);
4733 else if (*config
->old_plugins
[i
])
4736 remove_plugin(config
->old_plugins
[i
]);
4740 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
4741 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
4742 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
4743 if (!*config
->cluster_interface
)
4744 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
4746 if (!config
->cluster_hb_interval
)
4747 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
4749 if (!config
->cluster_hb_timeout
)
4750 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
4752 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
4754 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
4755 // late, ensure we're sufficiently larger than that
4756 int t
= 4 * config
->cluster_hb_interval
+ 11;
4758 if (config
->cluster_hb_timeout
< t
)
4760 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
4761 config
->cluster_hb_timeout
= t
;
4764 // Push timing changes to the slaves immediately if we're the master
4765 if (config
->cluster_iam_master
)
4766 cluster_heartbeat();
4768 interval
= config
->cluster_hb_interval
;
4769 timeout
= config
->cluster_hb_timeout
;
4773 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
4776 if ((f
= fopen(config
->pid_file
, "w")))
4778 fprintf(f
, "%d\n", getpid());
4780 config
->wrote_pid
= 1;
4784 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
4789 static void read_config_file()
4793 if (!config
->config_file
) return;
4794 if (!(f
= fopen(config
->config_file
, "r")))
4796 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
4800 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
4802 LOG(3, 0, 0, "Done reading config file\n");
4806 int sessionsetup(sessionidt s
, tunnelidt t
)
4808 // A session now exists, set it up
4814 CSTAT(sessionsetup
);
4816 LOG(3, s
, t
, "Doing session setup for session\n");
4820 assign_ip_address(s
);
4823 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
4824 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
4827 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
4828 fmtaddr(htonl(session
[s
].ip
), 0));
4832 // Make sure this is right
4833 session
[s
].tunnel
= t
;
4835 // Join a bundle if the MRRU option is accepted
4836 if (session
[s
].mrru
> 0 && !session
[s
].bundle
)
4838 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
4840 cluster_send_bundle(session
[s
].bundle
);
4843 // zap old sessions with same IP and/or username
4844 // Don't kill gardened sessions - doing so leads to a DoS
4845 // from someone who doesn't need to know the password
4848 user
= session
[s
].user
;
4849 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4851 if (i
== s
) continue;
4852 if (!session
[s
].opened
) continue;
4853 if (ip
== session
[i
].ip
)
4855 sessionkill(i
, "Duplicate IP address");
4859 if (config
->allow_duplicate_users
)
4862 if (session
[s
].walled_garden
|| session
[i
].walled_garden
)
4865 // Allow duplicate sessions for guest account.
4866 if (*config
->guest_user
&& !strcasecmp(user
, config
->guest_user
))
4869 // Allow duplicate sessions for multilink ones of the same bundle.
4870 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
4873 // Drop the new session in case of duplicate sessionss, not the old one.
4874 if (!strcasecmp(user
, session
[i
].user
))
4875 sessionkill(i
, "Duplicate session for users");
4882 // Add the route for this session.
4883 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
4885 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
4886 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
4889 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
4892 // Static IPs need to be routed if not already
4893 // convered by a Framed-Route. Anything else is part
4894 // of the IP address pool and is already routed, it
4895 // just needs to be added to the IP cache.
4896 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
4897 if (session
[s
].ip_pool_index
== -1) // static ip
4899 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
4902 cache_ipmap(session
[s
].ip
, s
);
4905 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
4906 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
4908 // Run the plugin's against this new session.
4910 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
4911 run_plugins(PLUGIN_NEW_SESSION
, &data
);
4914 // Allocate TBFs if throttled
4915 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
4916 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
4918 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
4920 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
4921 fmtaddr(htonl(session
[s
].ip
), 0),
4922 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
4924 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
4926 return 1; // RADIUS OK and IP allocated, done...
4930 // This session just got dropped on us by the master or something.
4931 // Make sure our tables up up to date...
4933 int load_session(sessionidt s
, sessiont
*new)
4939 if (new->ip_pool_index
>= MAXIPPOOL
||
4940 new->tunnel
>= MAXTUNNEL
)
4942 LOG(0, s
, 0, "Strange session update received!\n");
4943 // FIXME! What to do here?
4948 // Ok. All sanity checks passed. Now we're committed to
4949 // loading the new session.
4952 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
4954 // See if routes/ip cache need updating
4955 if (new->ip
!= session
[s
].ip
)
4958 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
4959 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
4960 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
4968 // remove old routes...
4969 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
4971 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
4972 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
4975 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
4981 if (session
[s
].ip_pool_index
== -1) // static IP
4983 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
4985 else // It's part of the IP pool, remove it manually.
4986 uncache_ipmap(session
[s
].ip
);
4991 // add new routes...
4992 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
4994 if ((new->ip
& new->route
[i
].mask
) ==
4995 (new->route
[i
].ip
& new->route
[i
].mask
))
4998 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
5004 // If there's a new one, add it.
5005 if (new->ip_pool_index
== -1)
5007 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5010 cache_ipmap(new->ip
, s
);
5015 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5016 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5019 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5021 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5025 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5027 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5028 new->filter_out
= 0;
5031 if (new->filter_in
!= session
[s
].filter_in
)
5033 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5034 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5037 if (new->filter_out
!= session
[s
].filter_out
)
5039 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5040 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5043 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5044 // for walking the sessions to forward byte counts to the master.
5045 config
->cluster_highest_sessionid
= s
;
5047 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5049 // Do fixups into address pool.
5050 if (new->ip_pool_index
!= -1)
5051 fix_address_pool(s
);
5056 static void initplugins()
5060 loaded_plugins
= ll_init();
5061 // Initialize the plugins to nothing
5062 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5063 plugins
[i
] = ll_init();
5066 static void *open_plugin(char *plugin_name
, int load
)
5068 char path
[256] = "";
5070 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5071 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5072 return dlopen(path
, RTLD_NOW
);
5075 // plugin callback to get a config value
5076 static void *getconfig(char *key
, enum config_typet type
)
5080 for (i
= 0; config_values
[i
].key
; i
++)
5082 if (!strcmp(config_values
[i
].key
, key
))
5084 if (config_values
[i
].type
== type
)
5085 return ((void *) config
) + config_values
[i
].offset
;
5087 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5088 key
, type
, config_values
[i
].type
);
5094 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5098 static int add_plugin(char *plugin_name
)
5100 static struct pluginfuncs funcs
= {
5105 sessiontbysessionidt
,
5106 sessionidtbysessiont
,
5113 cluster_send_session
,
5116 void *p
= open_plugin(plugin_name
, 1);
5117 int (*initfunc
)(struct pluginfuncs
*);
5122 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5126 if (ll_contains(loaded_plugins
, p
))
5129 return 0; // already loaded
5133 int *v
= dlsym(p
, "plugin_api_version");
5134 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5136 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5142 if ((initfunc
= dlsym(p
, "plugin_init")))
5144 if (!initfunc(&funcs
))
5146 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5152 ll_push(loaded_plugins
, p
);
5154 for (i
= 0; i
< max_plugin_functions
; i
++)
5157 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5159 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5160 ll_push(plugins
[i
], x
);
5164 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5168 static void run_plugin_done(void *plugin
)
5170 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5176 static int remove_plugin(char *plugin_name
)
5178 void *p
= open_plugin(plugin_name
, 0);
5184 if (ll_contains(loaded_plugins
, p
))
5187 for (i
= 0; i
< max_plugin_functions
; i
++)
5190 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5191 ll_delete(plugins
[i
], x
);
5194 ll_delete(loaded_plugins
, p
);
5200 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5204 int run_plugins(int plugin_type
, void *data
)
5206 int (*func
)(void *data
);
5208 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5209 return PLUGIN_RET_ERROR
;
5211 ll_reset(plugins
[plugin_type
]);
5212 while ((func
= ll_next(plugins
[plugin_type
])))
5216 if (r
!= PLUGIN_RET_OK
)
5217 return r
; // stop here
5220 return PLUGIN_RET_OK
;
5223 static void plugins_done()
5227 ll_reset(loaded_plugins
);
5228 while ((p
= ll_next(loaded_plugins
)))
5232 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5234 struct nsctl request
;
5235 struct nsctl response
;
5236 int type
= unpack_control(&request
, buf
, len
);
5240 if (log_stream
&& config
->debug
>= 4)
5244 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5245 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5249 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5250 dump_control(&request
, log_stream
);
5256 case NSCTL_REQ_LOAD
:
5257 if (request
.argc
!= 1)
5259 response
.type
= NSCTL_RES_ERR
;
5261 response
.argv
[0] = "name of plugin required";
5263 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5265 response
.type
= NSCTL_RES_ERR
;
5267 response
.argv
[0] = !r
5268 ? "plugin already loaded"
5269 : "error loading plugin";
5273 response
.type
= NSCTL_RES_OK
;
5279 case NSCTL_REQ_UNLOAD
:
5280 if (request
.argc
!= 1)
5282 response
.type
= NSCTL_RES_ERR
;
5284 response
.argv
[0] = "name of plugin required";
5286 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5288 response
.type
= NSCTL_RES_ERR
;
5290 response
.argv
[0] = !r
5291 ? "plugin not loaded"
5292 : "plugin not found";
5296 response
.type
= NSCTL_RES_OK
;
5302 case NSCTL_REQ_HELP
:
5303 response
.type
= NSCTL_RES_OK
;
5306 ll_reset(loaded_plugins
);
5307 while ((p
= ll_next(loaded_plugins
)))
5309 char **help
= dlsym(p
, "plugin_control_help");
5310 while (response
.argc
< 0xff && help
&& *help
)
5311 response
.argv
[response
.argc
++] = *help
++;
5316 case NSCTL_REQ_CONTROL
:
5318 struct param_control param
= {
5319 config
->cluster_iam_master
,
5326 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5328 if (r
== PLUGIN_RET_ERROR
)
5330 response
.type
= NSCTL_RES_ERR
;
5332 response
.argv
[0] = param
.additional
5334 : "error returned by plugin";
5336 else if (r
== PLUGIN_RET_NOTMASTER
)
5338 static char msg
[] = "must be run on master: 000.000.000.000";
5340 response
.type
= NSCTL_RES_ERR
;
5342 if (config
->cluster_master_address
)
5344 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5345 response
.argv
[0] = msg
;
5349 response
.argv
[0] = "must be run on master: none elected";
5352 else if (!(param
.response
& NSCTL_RESPONSE
))
5354 response
.type
= NSCTL_RES_ERR
;
5356 response
.argv
[0] = param
.response
5357 ? "unrecognised response value from plugin"
5358 : "unhandled action";
5362 response
.type
= param
.response
;
5364 if (param
.additional
)
5367 response
.argv
[0] = param
.additional
;
5375 response
.type
= NSCTL_RES_ERR
;
5377 response
.argv
[0] = "error unpacking control packet";
5380 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5383 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5387 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5390 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5391 if (log_stream
&& config
->debug
>= 4)
5393 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5394 dump_control(&response
, log_stream
);
5398 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5399 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5404 static tunnelidt
new_tunnel()
5407 for (i
= 1; i
< MAXTUNNEL
; i
++)
5409 if (tunnel
[i
].state
== TUNNELFREE
)
5411 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5412 if (i
> config
->cluster_highest_tunnelid
)
5413 config
->cluster_highest_tunnelid
= i
;
5417 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5422 // We're becoming the master. Do any required setup..
5424 // This is principally telling all the plugins that we're
5425 // now a master, and telling them about all the sessions
5426 // that are active too..
5428 void become_master(void)
5431 static struct event_data d
[RADIUS_FDS
];
5432 struct epoll_event e
;
5434 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5436 // running a bunch of iptables commands is slow and can cause
5437 // the master to drop tunnels on takeover--kludge around the
5438 // problem by forking for the moment (note: race)
5439 if (!fork_and_close())
5441 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5443 if (!session
[s
].opened
) // Not an in-use session.
5446 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5453 for (i
= 0; i
< RADIUS_FDS
; i
++)
5455 d
[i
].type
= FD_TYPE_RADIUS
;
5459 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5463 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5469 if (CLI_HELP_REQUESTED
)
5470 return CLI_HELP_NO_ARGS
;
5473 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5475 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5478 if (!session
[s
].opened
)
5481 idle
= time_now
- session
[s
].last_data
;
5482 idle
/= 5 ; // In multiples of 5 seconds.
5492 for (i
= 0; i
< 63; ++i
)
5494 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5496 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5497 cli_print(cli
, "%d total sessions open.", count
);
5501 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5507 if (CLI_HELP_REQUESTED
)
5508 return CLI_HELP_NO_ARGS
;
5511 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5513 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5516 if (!session
[s
].opened
)
5519 d
= time_now
- session
[s
].opened
;
5522 while (d
> 1 && open
< 32)
5532 for (i
= 0; i
< 30; ++i
)
5534 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5537 cli_print(cli
, "%d total sessions open.", count
);
5543 * This unencodes the AVP using the L2TP secret and the previously
5544 * stored random vector. It overwrites the hidden data with the
5545 * unhidden AVP subformat.
5547 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5553 uint16_t m
= htons(type
);
5555 // Compute initial pad
5557 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5558 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5559 MD5_Update(&ctx
, vector
, vec_len
);
5560 MD5_Final(digest
, &ctx
);
5562 // pointer to last decoded 16 octets
5567 // calculate a new pad based on the last decoded block
5568 if (d
>= sizeof(digest
))
5571 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5572 MD5_Update(&ctx
, last
, sizeof(digest
));
5573 MD5_Final(digest
, &ctx
);
5579 *value
++ ^= digest
[d
++];
5584 int find_filter(char const *name
, size_t len
)
5589 for (i
= 0; i
< MAXFILTER
; i
++)
5591 if (!*ip_filters
[i
].name
)
5599 if (strlen(ip_filters
[i
].name
) != len
)
5602 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5609 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5613 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5614 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5615 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5616 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5617 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5623 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5627 case FILTER_FLAG_OP_ANY
:
5628 return (flags
& sflags
) || (~flags
& cflags
);
5630 case FILTER_FLAG_OP_ALL
:
5631 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5633 case FILTER_FLAG_OP_EST
:
5634 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5640 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5642 uint16_t frag_offset
;
5646 uint16_t src_port
= 0;
5647 uint16_t dst_port
= 0;
5649 ip_filter_rulet
*rule
;
5651 if (len
< 20) // up to end of destination address
5654 if ((*buf
>> 4) != 4) // IPv4
5657 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5659 src_ip
= *(in_addr_t
*) (buf
+ 12);
5660 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5662 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5664 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5665 if (len
< l
+ 4) // ports
5668 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
5669 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
5670 if (proto
== IPPROTO_TCP
)
5672 if (len
< l
+ 14) // flags
5675 flags
= buf
[l
+ 13] & 0x3f;
5679 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
5681 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
5684 if (rule
->src_wild
!= INADDR_BROADCAST
&&
5685 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
5688 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
5689 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
5694 // layer 4 deny rules are skipped
5695 if (rule
->action
== FILTER_ACTION_DENY
&&
5696 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
5704 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
5706 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
5709 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
5712 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
5713 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
5720 return rule
->action
== FILTER_ACTION_PERMIT
;