3 // Copyright (c) 2003, 2004, 2005 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
7 char const *cvs_id_l2tpns
= "$Id: l2tpns.c,v 1.73.2.15 2005/05/31 12:09:33 bodea Exp $";
13 #include <linux/if_tun.h>
18 #include <net/route.h>
21 #include <netinet/in.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
31 #include <sys/resource.h>
39 #include <sys/sysinfo.h>
47 #include "constants.h"
57 configt
*config
= NULL
; // all configuration
58 int tunfd
= -1; // tun interface file handle. (network device)
59 int udpfd
= -1; // UDP file handle
60 int controlfd
= -1; // Control signal handle
61 int clifd
= -1; // Socket listening for CLI connections.
62 int snoopfd
= -1; // UDP file handle for sending out intercept data
63 int *radfds
= NULL
; // RADIUS requests file handles
64 int ifrfd
= -1; // File descriptor for routing, etc
65 time_t basetime
= 0; // base clock
66 char hostname
[1000] = ""; // us.
67 static uint32_t sessionid
= 0; // session id for radius accounting
68 static int syslog_log
= 0; // are we logging to syslog
69 static FILE *log_stream
= NULL
; // file handle for direct logging (i.e. direct into file, not via syslog).
70 extern int cluster_sockfd
; // Intra-cluster communications socket.
71 uint32_t last_id
= 0; // Last used PPP SID. Can I kill this?? -- mo
73 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
74 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
76 static void *ip_hash
[256]; // Mapping from IP address to session structures.
79 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
80 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
83 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
84 time_t time_now
= 0; // Current time in seconds since epoch.
85 static char time_now_string
[64] = {0}; // Current time as a string.
86 char main_quit
= 0; // True if we're in the process of exiting.
87 linked_list
*loaded_plugins
;
88 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
90 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
91 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
93 config_descriptt config_values
[] = {
94 CONFIG("debug", debug
, INT
),
95 CONFIG("log_file", log_filename
, STRING
),
96 CONFIG("pid_file", pid_file
, STRING
),
97 CONFIG("l2tp_secret", l2tpsecret
, STRING
),
98 CONFIG("primary_dns", default_dns1
, IP
),
99 CONFIG("secondary_dns", default_dns2
, IP
),
100 CONFIG("save_state", save_state
, BOOL
),
101 CONFIG("primary_radius", radiusserver
[0], IP
),
102 CONFIG("secondary_radius", radiusserver
[1], IP
),
103 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
104 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
105 CONFIG("radius_accounting", radius_accounting
, BOOL
),
106 CONFIG("radius_secret", radiussecret
, STRING
),
107 CONFIG("bind_address", bind_address
, IP
),
108 CONFIG("peer_address", peer_address
, IP
),
109 CONFIG("send_garp", send_garp
, BOOL
),
110 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
111 CONFIG("throttle_buckets", num_tbfs
, INT
),
112 CONFIG("accounting_dir", accounting_dir
, STRING
),
113 CONFIG("setuid", target_uid
, INT
),
114 CONFIG("dump_speed", dump_speed
, BOOL
),
115 CONFIG("multi_read_count", multi_read_count
, INT
),
116 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
117 CONFIG("lock_pages", lock_pages
, BOOL
),
118 CONFIG("icmp_rate", icmp_rate
, INT
),
119 CONFIG("packet_limit", max_packets
, INT
),
120 CONFIG("cluster_address", cluster_address
, IP
),
121 CONFIG("cluster_interface", cluster_interface
, STRING
),
122 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
123 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
124 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
128 static char *plugin_functions
[] = {
135 "plugin_new_session",
136 "plugin_kill_session",
138 "plugin_radius_response",
139 "plugin_become_master",
140 "plugin_new_session_master",
143 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
145 // Counters for shutdown sessions
146 static sessiont shut_acct
[8192];
147 static sessionidt shut_acct_n
= 0;
149 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
150 sessiont
*session
= NULL
; // Array of session structures.
151 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
152 radiust
*radius
= NULL
; // Array of radius structures.
153 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
154 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
155 static controlt
*controlfree
= 0;
156 struct Tstats
*_statistics
= NULL
;
158 struct Tringbuffer
*ringbuffer
= NULL
;
161 static void cache_ipmap(in_addr_t ip
, int s
);
162 static void uncache_ipmap(in_addr_t ip
);
163 static void free_ip_address(sessionidt s
);
164 static void dump_acct_info(int all
);
165 static void sighup_handler(int sig
);
166 static void sigalrm_handler(int sig
);
167 static void sigterm_handler(int sig
);
168 static void sigquit_handler(int sig
);
169 static void sigchild_handler(int sig
);
170 static void read_state(void);
171 static void dump_state(void);
172 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
);
173 static void update_config(void);
174 static void read_config_file(void);
175 static void initplugins(void);
176 static int add_plugin(char *plugin_name
);
177 static int remove_plugin(char *plugin_name
);
178 static void plugins_done(void);
179 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
);
180 static tunnelidt
new_tunnel(void);
181 static int unhide_avp(uint8_t *avp
, tunnelidt t
, sessionidt s
, uint16_t length
);
183 // on slaves, alow BGP to withdraw cleanly before exiting
186 // return internal time (10ths since process startup), set f if given
187 static clockt
now(double *f
)
191 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
192 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
195 // work out a retry time based on try number
196 // This is a straight bounded exponential backoff.
197 // Maximum re-try time is 32 seconds. (2^5).
198 clockt
backoff(uint8_t try)
200 if (try > 5) try = 5; // max backoff
201 return now(NULL
) + 10 * (1 << try);
206 // Log a debug message. Typically called via the LOG macro
208 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
210 static char message
[65536] = {0};
211 static char message2
[65536] = {0};
217 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
218 ringbuffer
->tail
= 0;
219 if (ringbuffer
->tail
== ringbuffer
->head
)
220 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
221 ringbuffer
->head
= 0;
223 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
224 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
225 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
226 va_start(ap
, format
);
227 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
232 if (config
->debug
< level
) return;
234 va_start(ap
, format
);
237 vsnprintf(message2
, 65535, format
, ap
);
238 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
239 fprintf(log_stream
, "%s", message
);
243 vsnprintf(message2
, 65535, format
, ap
);
244 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
245 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
250 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
253 const uint8_t *d
= (const uint8_t *) data
;
255 if (config
->debug
< level
) return;
257 // No support for _log_hex to syslog
260 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
261 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
263 for (i
= 0; i
< maxsize
; )
265 fprintf(log_stream
, "%4X: ", i
);
266 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
268 fprintf(log_stream
, "%02X ", d
[j
]);
270 fputs(": ", log_stream
);
273 for (; j
< i
+ 16; j
++)
275 fputs(" ", log_stream
);
277 fputs(": ", log_stream
);
280 fputs(" ", log_stream
);
281 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
283 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
284 fputc(d
[j
], log_stream
);
286 fputc('.', log_stream
);
289 fputs(" ", log_stream
);
293 fputs("\n", log_stream
);
297 setbuf(log_stream
, NULL
);
304 // This adds it to the routing table, advertises it
305 // via BGP if enabled, and stuffs it into the
306 // 'sessionbyip' cache.
308 // 'ip' and 'mask' must be in _host_ order.
310 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
315 if (!mask
) mask
= 0xffffffff;
317 ip
&= mask
; // Force the ip to be the first one in the route.
319 memset(&r
, 0, sizeof(r
));
320 r
.rt_dev
= config
->tundevice
;
321 r
.rt_dst
.sa_family
= AF_INET
;
322 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
323 r
.rt_gateway
.sa_family
= AF_INET
;
324 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
325 r
.rt_genmask
.sa_family
= AF_INET
;
326 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
327 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
329 r
.rt_flags
|= RTF_GATEWAY
;
330 else if (mask
== 0xffffffff)
331 r
.rt_flags
|= RTF_HOST
;
333 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
334 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
335 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
337 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
338 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
342 bgp_add_route(htonl(ip
), htonl(mask
));
344 bgp_del_route(htonl(ip
), htonl(mask
));
347 // Add/Remove the IPs to the 'sessionbyip' cache.
348 // Note that we add the zero address in the case of
349 // a network route. Roll on CIDR.
351 // Note that 's == 0' implies this is the address pool.
352 // We still cache it here, because it will pre-fill
353 // the malloc'ed tree.
357 if (!add
) // Are we deleting a route?
358 s
= 0; // Caching the session as '0' is the same as uncaching.
360 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
366 // Set up TUN interface
367 static void inittun(void)
370 struct sockaddr_in sin
= {0};
371 memset(&ifr
, 0, sizeof(ifr
));
372 ifr
.ifr_flags
= IFF_TUN
;
374 tunfd
= open(TUNDEVICE
, O_RDWR
);
377 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
381 int flags
= fcntl(tunfd
, F_GETFL
, 0);
382 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
384 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
386 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
389 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
390 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
391 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
393 sin
.sin_family
= AF_INET
;
394 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
395 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
397 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
399 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
402 /* Bump up the qlen to deal with bursts from the network */
404 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
406 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
409 ifr
.ifr_flags
= IFF_UP
;
410 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
412 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
418 static void initudp(void)
421 struct sockaddr_in addr
;
424 memset(&addr
, 0, sizeof(addr
));
425 addr
.sin_family
= AF_INET
;
426 addr
.sin_port
= htons(L2TPPORT
);
427 addr
.sin_addr
.s_addr
= config
->bind_address
;
428 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
429 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
431 int flags
= fcntl(udpfd
, F_GETFL
, 0);
432 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
434 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
436 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
439 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
442 memset(&addr
, 0, sizeof(addr
));
443 addr
.sin_family
= AF_INET
;
444 addr
.sin_port
= htons(NSCTL_PORT
);
445 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
446 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
447 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
449 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
455 // Find session by IP, < 1 for not found
457 // Confusingly enough, this 'ip' must be
458 // in _network_ order. This being the common
459 // case when looking it up from IP packet headers.
461 // We actually use this cache for two things.
462 // #1. For used IP addresses, this maps to the
463 // session ID that it's used by.
464 // #2. For un-used IP addresses, this maps to the
465 // index into the pool table that contains that
469 static int lookup_ipmap(in_addr_t ip
)
471 uint8_t *a
= (uint8_t *) &ip
;
472 uint8_t **d
= (uint8_t **) ip_hash
;
474 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
475 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
476 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
478 return (int) (intptr_t) d
[(size_t) *a
];
481 sessionidt
sessionbyip(in_addr_t ip
)
483 int s
= lookup_ipmap(ip
);
484 CSTAT(call_sessionbyip
);
486 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
487 return (sessionidt
) s
;
493 // Take an IP address in HOST byte order and
494 // add it to the sessionid by IP cache.
496 // (It's actually cached in network order)
498 static void cache_ipmap(in_addr_t ip
, int s
)
500 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
501 uint8_t *a
= (uint8_t *) &nip
;
502 uint8_t **d
= (uint8_t **) ip_hash
;
505 for (i
= 0; i
< 3; i
++)
507 if (!d
[(size_t) a
[i
]])
509 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof(void *))))
513 d
= (uint8_t **) d
[(size_t) a
[i
]];
516 d
[(size_t) a
[3]] = (uint8_t *) (intptr_t) s
;
519 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
522 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
523 // else a map to an ip pool index.
526 static void uncache_ipmap(in_addr_t ip
)
528 cache_ipmap(ip
, 0); // Assign it to the NULL session.
532 // CLI list to dump current ipcache.
534 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
536 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
540 if (CLI_HELP_REQUESTED
)
541 return CLI_HELP_NO_ARGS
;
543 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
545 for (i
= 0; i
< 256; ++i
)
550 for (j
= 0; j
< 256; ++j
)
555 for (k
= 0; k
< 256; ++k
)
560 for (l
= 0; l
< 256; ++l
)
564 cli_print(cli
, "%7d %d.%d.%d.%d", (int) (intptr_t) g
[l
], i
, j
, k
, l
);
570 cli_print(cli
, "%d entries in cache", count
);
575 // Find session by username, 0 for not found
576 // walled garden users aren't authenticated, so the username is
577 // reasonably useless. Ignore them to avoid incorrect actions
579 // This is VERY inefficent. Don't call it often. :)
581 sessionidt
sessionbyuser(char *username
)
584 CSTAT(call_sessionbyuser
);
586 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
588 if (!session
[s
].opened
)
591 if (session
[s
].walled_garden
)
592 continue; // Skip walled garden users.
594 if (!strncmp(session
[s
].user
, username
, 128))
598 return 0; // Not found.
601 void send_garp(in_addr_t ip
)
607 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
610 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
613 memset(&ifr
, 0, sizeof(ifr
));
614 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
615 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
617 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
621 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
622 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
624 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
629 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
632 static sessiont
*sessiontbysessionidt(sessionidt s
)
634 if (!s
|| s
>= MAXSESSION
) return NULL
;
638 static sessionidt
sessionidtbysessiont(sessiont
*s
)
640 sessionidt val
= s
-session
;
641 if (s
< session
|| val
>= MAXSESSION
) return 0;
645 // actually send a control message for a specific tunnel
646 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
648 struct sockaddr_in addr
;
650 CSTAT(call_tunnelsend
);
654 static int backtrace_count
= 0;
655 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
656 STAT(tunnel_tx_errors
);
657 log_backtrace(backtrace_count
, 5)
663 static int backtrace_count
= 0;
664 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
665 log_backtrace(backtrace_count
, 5)
666 STAT(tunnel_tx_errors
);
670 memset(&addr
, 0, sizeof(addr
));
671 addr
.sin_family
= AF_INET
;
672 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
673 addr
.sin_port
= htons(tunnel
[t
].port
);
675 // sequence expected, if sequence in message
676 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
678 // If this is a control message, deal with retries
681 tunnel
[t
].last
= time_now
; // control message sent
682 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
683 if (tunnel
[t
].try > 1)
685 STAT(tunnel_retries
);
686 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
690 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
692 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
693 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
694 STAT(tunnel_tx_errors
);
698 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
699 STAT(tunnel_tx_packets
);
700 INC_STAT(tunnel_tx_bytes
, l
);
704 // Tiny helper function to write data to
707 int tun_write(uint8_t * data
, int size
)
709 return write(tunfd
, data
, size
);
712 // process outgoing (to tunnel) IP
714 static void processipout(uint8_t * buf
, int len
)
721 char *data
= buf
; // Keep a copy of the originals.
724 uint8_t b
[MAXETHER
+ 20];
726 CSTAT(call_processipout
);
728 if (len
< MIN_IP_SIZE
)
730 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
736 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
741 // Skip the tun header
745 // Got an IP header now
746 if (*(uint8_t *)(buf
) >> 4 != 4)
748 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
752 ip
= *(uint32_t *)(buf
+ 16);
753 if (!(s
= sessionbyip(ip
)))
755 // Is this a packet for a session that doesn't exist?
756 static int rate
= 0; // Number of ICMP packets we've sent this second.
757 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
759 if (last
!= time_now
)
765 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
767 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
768 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
772 t
= session
[s
].tunnel
;
775 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
776 if (config
->max_packets
> 0)
778 if (sess_local
[s
].last_packet_out
== TIME
)
780 int max
= config
->max_packets
;
782 // All packets for throttled sessions are handled by the
783 // master, so further limit by using the throttle rate.
784 // A bit of a kludge, since throttle rate is in kbps,
785 // but should still be generous given our average DSL
786 // packet size is 200 bytes: a limit of 28kbps equates
787 // to around 180 packets per second.
788 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
789 max
= sp
->throttle_out
;
791 if (++sess_local
[s
].packets_out
> max
)
793 sess_local
[s
].packets_dropped
++;
799 if (sess_local
[s
].packets_dropped
)
801 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
802 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
803 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
804 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
808 sess_local
[s
].last_packet_out
= TIME
;
809 sess_local
[s
].packets_out
= 1;
810 sess_local
[s
].packets_dropped
= 0;
814 // run access-list if any
815 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
820 // Are we throttling this session?
821 if (config
->cluster_iam_master
)
822 tbf_queue_packet(sp
->tbf_out
, data
, size
);
824 master_throttle_packet(sp
->tbf_out
, data
, size
);
827 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
829 // We are walled-gardening this
830 master_garden_packet(s
, data
, size
);
834 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
836 // Add on L2TP header
838 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
840 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
843 // Snooping this session, send it to intercept box
844 if (sp
->snoop_ip
&& sp
->snoop_port
)
845 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
847 sp
->cout
+= len
; // byte count
848 sp
->total_cout
+= len
; // byte count
851 sess_local
[s
].cout
+= len
; // To send to master..
855 // Helper routine for the TBF filters.
856 // Used to send queued data in to the user!
858 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
864 uint8_t b
[MAXETHER
+ 20];
866 if (len
< 0 || len
> MAXETHER
)
868 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
872 // Skip the tun header
876 ip
= *(in_addr_t
*)(buf
+ 16);
881 t
= session
[s
].tunnel
;
884 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
886 // Add on L2TP header
888 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
890 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
893 // Snooping this session.
894 if (sp
->snoop_ip
&& sp
->snoop_port
)
895 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
897 sp
->cout
+= len
; // byte count
898 sp
->total_cout
+= len
; // byte count
901 sess_local
[s
].cout
+= len
; // To send to master..
904 // add an AVP (16 bit)
905 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
907 uint16_t l
= (m
? 0x8008 : 0x0008);
908 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
909 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
910 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
911 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
915 // add an AVP (32 bit)
916 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
918 uint16_t l
= (m
? 0x800A : 0x000A);
919 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
920 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
921 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
922 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
926 // add an AVP (32 bit)
927 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
929 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
930 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
931 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
932 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
933 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
934 c
->length
+= 6 + strlen(val
);
938 static void controlb(controlt
* c
, uint16_t avp
, char *val
, unsigned int len
, uint8_t m
)
940 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
941 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
942 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
943 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
944 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
945 c
->length
+= 6 + len
;
948 // new control connection
949 static controlt
*controlnew(uint16_t mtype
)
953 c
= malloc(sizeof(controlt
));
957 controlfree
= c
->next
;
961 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
963 control16(c
, 0, mtype
, 1);
967 // send zero block if nothing is waiting
969 static void controlnull(tunnelidt t
)
972 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
975 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
976 *(uint16_t *) (buf
+ 2) = htons(12); // length
977 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
978 *(uint16_t *) (buf
+ 6) = htons(0); // session
979 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
980 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
981 tunnelsend(buf
, 12, t
);
984 // add a control message to a tunnel, and send if within window
985 static void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
987 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
988 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
989 *(uint16_t *) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
990 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
991 tunnel
[t
].ns
++; // advance sequence
992 // link in message in to queue
993 if (tunnel
[t
].controlc
)
994 tunnel
[t
].controle
->next
= c
;
996 tunnel
[t
].controls
= c
;
998 tunnel
[t
].controle
= c
;
999 tunnel
[t
].controlc
++;
1001 // send now if space in window
1002 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1004 tunnel
[t
].try = 0; // first send
1005 tunnelsend(c
->buf
, c
->length
, t
);
1010 // Throttle or Unthrottle a session
1012 // Throttle the data from/to through a session to no more than
1013 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1016 // If either value is -1, the current value is retained for that
1019 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1021 if (!session
[s
].opened
)
1022 return; // No-one home.
1024 if (!*session
[s
].user
)
1025 return; // User not logged in
1029 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1030 if (session
[s
].tbf_in
)
1031 free_tbf(session
[s
].tbf_in
);
1034 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1036 session
[s
].tbf_in
= 0;
1038 session
[s
].throttle_in
= rate_in
;
1043 int bytes
= rate_out
* 1024 / 8;
1044 if (session
[s
].tbf_out
)
1045 free_tbf(session
[s
].tbf_out
);
1048 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1050 session
[s
].tbf_out
= 0;
1052 session
[s
].throttle_out
= rate_out
;
1056 // add/remove filters from session (-1 = no change)
1057 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1059 if (!session
[s
].opened
)
1060 return; // No-one home.
1062 if (!*session
[s
].user
)
1063 return; // User not logged in
1066 if (filter_in
> MAXFILTER
) filter_in
= -1;
1067 if (filter_out
> MAXFILTER
) filter_out
= -1;
1068 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1069 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1073 if (session
[s
].filter_in
)
1074 ip_filters
[session
[s
].filter_in
- 1].used
--;
1077 ip_filters
[filter_in
- 1].used
++;
1079 session
[s
].filter_in
= filter_in
;
1082 if (filter_out
>= 0)
1084 if (session
[s
].filter_out
)
1085 ip_filters
[session
[s
].filter_out
- 1].used
--;
1088 ip_filters
[filter_out
- 1].used
++;
1090 session
[s
].filter_out
= filter_out
;
1094 // start tidy shutdown of session
1095 void sessionshutdown(sessionidt s
, char *reason
)
1097 int walled_garden
= session
[s
].walled_garden
;
1100 CSTAT(call_sessionshutdown
);
1102 if (!session
[s
].opened
)
1104 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1105 return; // not a live session
1108 if (!session
[s
].die
)
1110 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1111 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1112 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1115 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1117 // RADIUS Stop message
1118 uint16_t r
= session
[s
].radius
;
1121 if (!(r
= radiusnew(s
)))
1123 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1128 for (n
= 0; n
< 15; n
++)
1129 radius
[r
].auth
[n
] = rand();
1133 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1134 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1136 // Save counters to dump to accounting file
1137 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1138 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1142 { // IP allocated, clear and unroute
1145 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1147 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1148 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1151 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1152 session
[s
].route
[r
].ip
= 0;
1155 if (session
[s
].ip_pool_index
== -1) // static ip
1157 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1164 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1165 throttle_session(s
, 0, 0);
1168 controlt
*c
= controlnew(14); // sending CDN
1169 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1170 control16(c
, 14, s
, 1); // assigned session (our end)
1171 controladd(c
, session
[s
].tunnel
, s
); // send the message
1174 if (!session
[s
].die
)
1175 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1177 // update filter refcounts
1178 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1179 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1181 cluster_send_session(s
);
1184 void sendipcp(tunnelidt t
, sessionidt s
)
1186 uint8_t buf
[MAXCONTROL
];
1187 uint16_t r
= session
[s
].radius
;
1190 CSTAT(call_sendipcp
);
1197 sessionshutdown(s
, "No free RADIUS sessions for IPCP");
1201 if (radius
[r
].state
!= RADIUSIPCP
)
1203 radius
[r
].state
= RADIUSIPCP
;
1207 radius
[r
].retry
= backoff(radius
[r
].try++);
1208 if (radius
[r
].try > 10)
1210 radiusclear(r
, s
); // Clear radius session.
1211 sessionshutdown(s
, "No reply on IPCP");
1215 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1219 q
[1] = r
>> RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1220 *(uint16_t *) (q
+ 2) = htons(10);
1223 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1224 config
->bind_address
? config
->bind_address
:
1225 my_address
; // send my IP
1227 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1228 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1231 static void sessionclear(sessionidt s
)
1233 memset(&session
[s
], 0, sizeof(session
[s
]));
1234 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
1235 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
1237 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1238 session
[s
].next
= sessionfree
;
1242 // kill a session now
1243 void sessionkill(sessionidt s
, char *reason
)
1246 CSTAT(call_sessionkill
);
1248 if (!session
[s
].opened
) // not alive
1251 if (session
[s
].next
)
1253 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%d)\n", session
[s
].next
);
1257 session
[s
].die
= TIME
;
1258 sessionshutdown(s
, reason
); // close radius/routes, etc.
1259 if (session
[s
].radius
)
1260 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1262 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1264 cluster_send_session(s
);
1267 static void tunnelclear(tunnelidt t
)
1270 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1271 tunnel
[t
].state
= TUNNELFREE
;
1274 // kill a tunnel now
1275 static void tunnelkill(tunnelidt t
, char *reason
)
1280 CSTAT(call_tunnelkill
);
1282 tunnel
[t
].state
= TUNNELDIE
;
1284 // free control messages
1285 while ((c
= tunnel
[t
].controls
))
1287 controlt
* n
= c
->next
;
1288 tunnel
[t
].controls
= n
;
1289 tunnel
[t
].controlc
--;
1290 c
->next
= controlfree
;
1294 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1295 if (session
[s
].tunnel
== t
)
1296 sessionkill(s
, reason
);
1300 LOG(1, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1301 cli_tunnel_actions
[s
].action
= 0;
1302 cluster_send_tunnel(t
);
1305 // shut down a tunnel cleanly
1306 static void tunnelshutdown(tunnelidt t
, char *reason
)
1310 CSTAT(call_tunnelshutdown
);
1312 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1314 // never set up, can immediately kill
1315 tunnelkill(t
, reason
);
1318 LOG(1, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1321 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1322 if (session
[s
].tunnel
== t
)
1323 sessionshutdown(s
, reason
);
1325 tunnel
[t
].state
= TUNNELDIE
;
1326 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
1327 cluster_send_tunnel(t
);
1328 // TBA - should we wait for sessions to stop?
1330 controlt
*c
= controlnew(4); // sending StopCCN
1331 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message)
1332 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1333 controladd(c
, t
, 0); // send the message
1337 // read and process packet on tunnel (UDP)
1338 void processudp(uint8_t * buf
, int len
, struct sockaddr_in
*addr
)
1340 char *chapresponse
= NULL
;
1341 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1342 uint8_t *p
= buf
+ 2;
1345 CSTAT(call_processudp
);
1349 LOG_HEX(5, "UDP Data", buf
, len
);
1350 STAT(tunnel_rx_packets
);
1351 INC_STAT(tunnel_rx_bytes
, len
);
1354 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
1355 STAT(tunnel_rx_errors
);
1358 if ((buf
[1] & 0x0F) != 2)
1360 LOG(1, 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1361 STAT(tunnel_rx_errors
);
1366 l
= ntohs(*(uint16_t *) p
);
1369 t
= ntohs(*(uint16_t *) p
);
1371 s
= ntohs(*(uint16_t *) p
);
1373 if (s
>= MAXSESSION
)
1375 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
1376 STAT(tunnel_rx_errors
);
1381 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
1382 STAT(tunnel_rx_errors
);
1387 ns
= ntohs(*(uint16_t *) p
);
1389 nr
= ntohs(*(uint16_t *) p
);
1394 uint16_t o
= ntohs(*(uint16_t *) p
);
1399 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
1400 STAT(tunnel_rx_errors
);
1406 uint16_t message
= 0xFFFF; // message type
1408 uint8_t mandatorymessage
= 0;
1409 uint8_t chap
= 0; // if CHAP being used
1410 uint16_t asession
= 0; // assigned session
1411 uint32_t amagic
= 0; // magic number
1412 uint8_t aflags
= 0; // flags from last LCF
1413 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1414 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1415 char called
[MAXTEL
] = ""; // called number
1416 char calling
[MAXTEL
] = ""; // calling number
1418 if (!config
->cluster_iam_master
)
1420 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1424 if ((*buf
& 0xCA) != 0xC8)
1426 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
1427 STAT(tunnel_rx_errors
);
1431 // check for duplicate tunnel open message
1437 // Is this a duplicate of the first packet? (SCCRQ)
1439 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1441 if (tunnel
[i
].state
!= TUNNELOPENING
||
1442 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
1443 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1446 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
1451 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1452 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1454 // if no tunnel specified, assign one
1457 if (!(t
= new_tunnel()))
1459 LOG(1, 0, 0, "No more tunnels\n");
1460 STAT(tunnel_overflow
);
1464 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
1465 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1466 tunnel
[t
].window
= 4; // default window
1467 STAT(tunnel_created
);
1468 LOG(1, 0, t
, " New tunnel from %s:%u ID %d\n",
1469 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
1472 // If the 'ns' just received is not the 'nr' we're
1473 // expecting, just send an ack and drop it.
1475 // if 'ns' is less, then we got a retransmitted packet.
1476 // if 'ns' is greater than missed a packet. Either way
1477 // we should ignore it.
1478 if (ns
!= tunnel
[t
].nr
)
1480 // is this the sequence we were expecting?
1481 STAT(tunnel_rx_errors
);
1482 LOG(1, 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n",
1483 t
, ns
, tunnel
[t
].nr
);
1485 if (l
) // Is this not a ZLB?
1490 // This is used to time out old tunnels
1491 tunnel
[t
].lastrec
= time_now
;
1493 // check sequence of this message
1495 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1496 // some to clear maybe?
1497 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1499 controlt
*c
= tunnel
[t
].controls
;
1500 tunnel
[t
].controls
= c
->next
;
1501 tunnel
[t
].controlc
--;
1502 c
->next
= controlfree
;
1505 tunnel
[t
].try = 0; // we have progress
1508 // receiver advance (do here so quoted correctly in any sends below)
1509 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1510 if (skip
< 0) skip
= 0;
1511 if (skip
< tunnel
[t
].controlc
)
1513 // some control packets can now be sent that were previous stuck out of window
1514 int tosend
= tunnel
[t
].window
- skip
;
1515 controlt
*c
= tunnel
[t
].controls
;
1523 tunnel
[t
].try = 0; // first send
1524 tunnelsend(c
->buf
, c
->length
, t
);
1529 if (!tunnel
[t
].controlc
)
1530 tunnel
[t
].retry
= 0; // caught up
1533 { // if not a null message
1535 while (l
&& !(fatal
& 0x80))
1537 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
1544 LOG(1, s
, t
, "Invalid length in AVP\n");
1545 STAT(tunnel_rx_errors
);
1552 // handle hidden AVPs
1553 if (!*config
->l2tpsecret
)
1555 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1559 if (!session
[s
].random_vector_length
)
1561 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
1565 LOG(4, s
, t
, "Hidden AVP\n");
1567 n
= unhide_avp(b
, t
, s
, n
);
1576 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1581 if (*(uint16_t *) (b
))
1583 LOG(2, s
, t
, "Unknown AVP vendor %d\n", ntohs(*(uint16_t *) (b
)));
1588 mtype
= ntohs(*(uint16_t *) (b
));
1592 LOG(4, s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1595 case 0: // message type
1596 message
= ntohs(*(uint16_t *) b
);
1597 LOG(4, s
, t
, " Message type = %d (%s)\n", *b
, l2tp_message_types
[message
]);
1598 mandatorymessage
= flags
;
1600 case 1: // result code
1602 uint16_t rescode
= ntohs(*(uint16_t *) b
);
1603 const char* resdesc
= "(unknown)";
1606 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1607 resdesc
= stopccn_result_codes
[rescode
];
1609 else if (message
== 14)
1611 if (rescode
<= MAX_CDN_RESULT_CODE
)
1612 resdesc
= cdn_result_codes
[rescode
];
1615 LOG(4, s
, t
, " Result Code %d: %s\n", rescode
, resdesc
);
1618 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
1619 const char* errdesc
= "(unknown)";
1620 if (errcode
<= MAX_ERROR_CODE
)
1621 errdesc
= error_codes
[errcode
];
1622 LOG(4, s
, t
, " Error Code %d: %s\n", errcode
, errdesc
);
1625 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
1630 case 2: // protocol version
1632 version
= ntohs(*(uint16_t *) (b
));
1633 LOG(4, s
, t
, " Protocol version = %d\n", version
);
1634 if (version
&& version
!= 0x0100)
1635 { // allow 0.0 and 1.0
1636 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
1642 case 3: // framing capabilities
1643 // LOG(4, s, t, "Framing capabilities\n");
1645 case 4: // bearer capabilities
1646 // LOG(4, s, t, "Bearer capabilities\n");
1648 case 5: // tie breaker
1649 // We never open tunnels, so we don't care about tie breakers
1650 // LOG(4, s, t, "Tie breaker\n");
1652 case 6: // firmware revision
1653 // LOG(4, s, t, "Firmware revision\n");
1655 case 7: // host name
1656 memset(tunnel
[t
].hostname
, 0, 128);
1657 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1658 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1659 // TBA - to send to RADIUS
1661 case 8: // vendor name
1662 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1663 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1664 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1666 case 9: // assigned tunnel
1667 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
1668 LOG(4, s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1670 case 10: // rx window
1671 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
1672 if (!tunnel
[t
].window
)
1673 tunnel
[t
].window
= 1; // window of 0 is silly
1674 LOG(4, s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1676 case 11: // Challenge
1678 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
1679 build_chap_response(b
, 2, n
, &chapresponse
);
1682 case 13: // Response
1683 // Why did they send a response? We never challenge.
1684 LOG(2, s
, t
, " received unexpected challenge response\n");
1687 case 14: // assigned session
1688 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
1689 LOG(4, s
, t
, " assigned session = %d\n", asession
);
1691 case 15: // call serial number
1692 LOG(4, s
, t
, " call serial number = %d\n", ntohl(*(uint32_t *)b
));
1694 case 18: // bearer type
1695 LOG(4, s
, t
, " bearer type = %d\n", ntohl(*(uint32_t *)b
));
1698 case 19: // framing type
1699 LOG(4, s
, t
, " framing type = %d\n", ntohl(*(uint32_t *)b
));
1702 case 21: // called number
1703 memset(called
, 0, MAXTEL
);
1704 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1705 LOG(4, s
, t
, " Called <%s>\n", called
);
1707 case 22: // calling number
1708 memset(calling
, 0, MAXTEL
);
1709 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1710 LOG(4, s
, t
, " Calling <%s>\n", calling
);
1714 case 24: // tx connect speed
1717 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
1721 // AS5300s send connect speed as a string
1723 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1724 session
[s
].tx_connect_speed
= atol(tmp
);
1726 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
1728 case 38: // rx connect speed
1731 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
1735 // AS5300s send connect speed as a string
1737 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1738 session
[s
].rx_connect_speed
= atol(tmp
);
1740 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
1742 case 25: // Physical Channel ID
1744 uint32_t tmp
= ntohl(*(uint32_t *) b
);
1745 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
1748 case 29: // Proxy Authentication Type
1750 uint16_t authtype
= ntohs(*(uint16_t *)b
);
1751 LOG(4, s
, t
, " Proxy Auth Type %d (%s)\n", authtype
, authtypes
[authtype
]);
1752 requestchap
= (authtype
== 2);
1755 case 30: // Proxy Authentication Name
1757 char authname
[64] = {0};
1758 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1759 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
1763 case 31: // Proxy Authentication Challenge
1765 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1766 LOG(4, s
, t
, " Proxy Auth Challenge\n");
1769 case 32: // Proxy Authentication ID
1771 uint16_t authid
= ntohs(*(uint16_t *)(b
));
1772 LOG(4, s
, t
, " Proxy Auth ID (%d)\n", authid
);
1773 if (session
[s
].radius
)
1774 radius
[session
[s
].radius
].id
= authid
;
1777 case 33: // Proxy Authentication Response
1779 char authresp
[64] = {0};
1780 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1781 LOG(4, s
, t
, " Proxy Auth Response\n");
1784 case 27: // last send lcp
1785 { // find magic number
1786 uint8_t *p
= b
, *e
= p
+ n
;
1787 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1789 if (*p
== 5 && p
[1] == 6) // Magic-Number
1790 amagic
= ntohl(*(uint32_t *) (p
+ 2));
1791 else if (*p
== 3 && p
[1] == 5 && *(uint16_t *) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1793 else if (*p
== 7) // Protocol-Field-Compression
1794 aflags
|= SESSIONPFC
;
1795 else if (*p
== 8) // Address-and-Control-Field-Compression
1796 aflags
|= SESSIONACFC
;
1801 case 28: // last recv lcp confreq
1803 case 26: // Initial Received LCP CONFREQ
1805 case 39: // seq required - we control it as an LNS anyway...
1807 case 36: // Random Vector
1808 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1809 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1810 memcpy(session
[s
].random_vector
, b
, n
);
1811 session
[s
].random_vector_length
= n
;
1814 LOG(2, s
, t
, " Unknown AVP type %d\n", mtype
);
1821 tunnelshutdown(t
, "Unknown Mandatory AVP");
1825 case 1: // SCCRQ - Start Control Connection Request
1827 controlt
*c
= controlnew(2); // sending SCCRP
1828 control16(c
, 2, version
, 1); // protocol version
1829 control32(c
, 3, 3, 1); // framing
1830 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1831 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1832 control16(c
, 9, t
, 1); // assigned tunnel
1833 controladd(c
, t
, s
); // send the resply
1835 tunnel
[t
].state
= TUNNELOPENING
;
1838 tunnel
[t
].state
= TUNNELOPEN
;
1841 tunnel
[t
].state
= TUNNELOPEN
;
1842 controlnull(t
); // ack
1845 controlnull(t
); // ack
1846 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1847 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1850 controlnull(t
); // simply ACK
1864 STAT(session_overflow
);
1865 LOG(1, 0, t
, "No free sessions\n");
1874 sessionfree
= session
[s
].next
;
1875 memset(&session
[s
], 0, sizeof(session
[s
]));
1877 if (s
> config
->cluster_highest_sessionid
)
1878 config
->cluster_highest_sessionid
= s
;
1880 // make a RADIUS session
1881 if (!(r
= radiusnew(s
)))
1883 LOG(1, s
, t
, "No free RADIUS sessions for ICRQ\n");
1888 c
= controlnew(11); // sending ICRP
1889 session
[s
].id
= sessionid
++;
1890 session
[s
].opened
= time_now
;
1891 session
[s
].tunnel
= t
;
1892 session
[s
].far
= asession
;
1893 session
[s
].last_packet
= time_now
;
1894 LOG(3, s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1895 control16(c
, 14, s
, 1); // assigned session
1896 controladd(c
, t
, s
); // send the reply
1898 // Generate a random challenge
1900 for (n
= 0; n
< 15; n
++)
1901 radius
[r
].auth
[n
] = rand();
1903 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1904 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1905 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1906 STAT(session_created
);
1913 if (amagic
== 0) amagic
= time_now
;
1914 session
[s
].magic
= amagic
; // set magic number
1915 session
[s
].l2tp_flags
= aflags
; // set flags received
1916 LOG(3, s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1917 controlnull(t
); // ack
1918 // In CHAP state, request PAP instead
1923 controlnull(t
); // ack
1924 sessionshutdown(s
, "Closed (Received CDN)");
1927 LOG(1, s
, t
, "Missing message type\n");
1930 STAT(tunnel_rx_errors
);
1931 if (mandatorymessage
& 0x80)
1932 tunnelshutdown(t
, "Unknown message");
1934 LOG(1, s
, t
, "Unknown message type %d\n", message
);
1937 if (chapresponse
) free(chapresponse
);
1938 cluster_send_tunnel(t
);
1942 LOG(4, s
, t
, " Got a ZLB ack\n");
1949 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
1950 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1951 { // HDLC address header, discard
1957 LOG(1, s
, t
, "Short ppp length %d\n", l
);
1958 STAT(tunnel_rx_errors
);
1968 prot
= ntohs(*(uint16_t *) p
);
1973 if (s
&& !session
[s
].opened
) // Is something wrong??
1975 if (!config
->cluster_iam_master
)
1977 // Pass it off to the master to deal with..
1978 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1982 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
1983 STAT(tunnel_rx_errors
);
1989 session
[s
].last_packet
= time_now
;
1990 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1991 processpap(t
, s
, p
, l
);
1993 else if (prot
== PPPCHAP
)
1995 session
[s
].last_packet
= time_now
;
1996 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1997 processchap(t
, s
, p
, l
);
1999 else if (prot
== PPPLCP
)
2001 session
[s
].last_packet
= time_now
;
2002 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2003 processlcp(t
, s
, p
, l
);
2005 else if (prot
== PPPIPCP
)
2007 session
[s
].last_packet
= time_now
;
2008 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2009 processipcp(t
, s
, p
, l
);
2011 else if (prot
== PPPCCP
)
2013 session
[s
].last_packet
= time_now
;
2014 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2015 processccp(t
, s
, p
, l
);
2017 else if (prot
== PPPIP
)
2021 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
2022 return; // closing session, PPP not processed
2025 session
[s
].last_packet
= time_now
;
2026 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2028 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2032 processipin(t
, s
, p
, l
);
2036 STAT(tunnel_rx_errors
);
2037 LOG(1, s
, t
, "Unknown PPP protocol %04X\n", prot
);
2042 // read and process packet on tun
2043 static void processtun(uint8_t * buf
, int len
)
2045 LOG_HEX(5, "Receive TUN Data", buf
, len
);
2046 STAT(tun_rx_packets
);
2047 INC_STAT(tun_rx_bytes
, len
);
2049 CSTAT(call_processtun
);
2055 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
2056 STAT(tun_rx_errors
);
2060 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IP
2061 processipout(buf
, len
);
2065 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
2066 // that we look at the whole of the tunnel, radius and session tables
2068 static void regular_cleanups(double period
)
2070 // Next tunnel, radius and session to check for actions on.
2071 static tunnelidt t
= 0;
2073 static sessionidt s
= 0;
2086 // divide up tables into slices based on the last run
2087 t_slice
= config
->cluster_highest_tunnelid
* period
;
2088 r_slice
= (MAXRADIUS
- 1) * period
;
2089 s_slice
= config
->cluster_highest_sessionid
* period
;
2093 else if (t_slice
> config
->cluster_highest_tunnelid
)
2094 t_slice
= config
->cluster_highest_tunnelid
;
2098 else if (r_slice
> (MAXRADIUS
- 1))
2099 r_slice
= MAXRADIUS
- 1;
2103 else if (s_slice
> config
->cluster_highest_sessionid
)
2104 s_slice
= config
->cluster_highest_sessionid
;
2106 LOG(5, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
2108 for (i
= 0; i
< t_slice
; i
++)
2111 if (t
> config
->cluster_highest_tunnelid
)
2114 // check for expired tunnels
2115 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2117 STAT(tunnel_timeout
);
2118 tunnelkill(t
, "Expired");
2122 // check for message resend
2123 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2125 // resend pending messages as timeout on reply
2126 if (tunnel
[t
].retry
<= TIME
)
2128 controlt
*c
= tunnel
[t
].controls
;
2129 uint8_t w
= tunnel
[t
].window
;
2130 tunnel
[t
].try++; // another try
2131 if (tunnel
[t
].try > 5)
2132 tunnelkill(t
, "Timeout on control message"); // game over
2136 tunnelsend(c
->buf
, c
->length
, t
);
2144 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2146 controlt
*c
= controlnew(6); // sending HELLO
2147 controladd(c
, t
, 0); // send the message
2148 LOG(3, 0, t
, "Sending HELLO message\n");
2152 // Check for tunnel changes requested from the CLI
2153 if ((a
= cli_tunnel_actions
[t
].action
))
2155 cli_tunnel_actions
[t
].action
= 0;
2156 if (a
& CLI_TUN_KILL
)
2158 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
2159 tunnelshutdown(t
, "Requested by administrator");
2165 for (i
= 0; i
< r_slice
; i
++)
2171 if (!radius
[r
].state
)
2174 if (radius
[r
].retry
<= TIME
)
2181 for (i
= 0; i
< s_slice
; i
++)
2184 if (s
> config
->cluster_highest_sessionid
)
2187 if (!session
[s
].opened
) // Session isn't in use
2190 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2192 // IPCP has not completed yet. Resend
2193 LOG(3, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2194 sendipcp(session
[s
].tunnel
, s
);
2198 // check for expired sessions
2199 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2201 sessionkill(s
, "Expired");
2206 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2207 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2209 sessionshutdown(s
, "No response to LCP ECHO requests");
2210 STAT(session_timeout
);
2215 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2216 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2218 uint8_t b
[MAXCONTROL
] = {0};
2220 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2224 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
2225 *(uint16_t *)(q
+ 2) = htons(8); // Length
2226 *(uint32_t *)(q
+ 4) = 0; // Magic Number (not supported)
2228 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2229 (int)(time_now
- session
[s
].last_packet
));
2230 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2234 // Check for actions requested from the CLI
2235 if ((a
= cli_session_actions
[s
].action
))
2239 cli_session_actions
[s
].action
= 0;
2240 if (a
& CLI_SESS_KILL
)
2242 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2243 sessionshutdown(s
, "Requested by administrator");
2244 a
= 0; // dead, no need to check for other actions
2248 if (a
& CLI_SESS_NOSNOOP
)
2250 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2251 session
[s
].snoop_ip
= 0;
2252 session
[s
].snoop_port
= 0;
2256 else if (a
& CLI_SESS_SNOOP
)
2258 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2259 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
2260 cli_session_actions
[s
].snoop_port
);
2262 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2263 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2268 if (a
& CLI_SESS_NOTHROTTLE
)
2270 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2271 throttle_session(s
, 0, 0);
2275 else if (a
& CLI_SESS_THROTTLE
)
2277 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2278 cli_session_actions
[s
].throttle_in
,
2279 cli_session_actions
[s
].throttle_out
);
2281 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2286 if (a
& CLI_SESS_NOFILTER
)
2288 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
2289 filter_session(s
, 0, 0);
2293 else if (a
& CLI_SESS_FILTER
)
2295 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
2296 cli_session_actions
[s
].filter_in
,
2297 cli_session_actions
[s
].filter_out
);
2299 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
2305 cluster_send_session(s
);
2309 LOG((t_actions
|| r_actions
|| s_actions
) ? 3 : 4, 0, 0,
2310 "Regular cleanup: processed %d tunnels, %d radius and %d sessions\n",
2311 t_actions
, r_actions
, s_actions
);
2313 LOG(5, 0, 0, "End regular cleanup: checked %d tunnels, %d radius and %d sessions\n",
2314 t_slice
, r_slice
, s_slice
);
2318 // Are we in the middle of a tunnel update, or radius
2321 static int still_busy(void)
2324 static time_t stopped_bgp
= 0;
2325 static clockt last_talked
= 0;
2326 static clockt start_busy_wait
= 0;
2328 if (!config
->cluster_iam_master
)
2335 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
2337 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2338 if (bgp_peers
[i
].state
== Established
)
2339 bgp_stop(&bgp_peers
[i
]);
2341 stopped_bgp
= time_now
;
2343 // we don't want to become master
2344 cluster_send_ping(0);
2349 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
2357 if (start_busy_wait
== 0)
2358 start_busy_wait
= TIME
;
2360 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2362 if (!tunnel
[i
].controlc
)
2365 if (last_talked
!= TIME
)
2367 LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i
);
2373 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2374 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2376 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2380 for (i
= 1; i
< MAXRADIUS
; i
++)
2382 if (radius
[i
].state
== RADIUSNULL
)
2384 if (radius
[i
].state
== RADIUSWAIT
)
2387 if (last_talked
!= TIME
)
2389 LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2398 static fd_set readset
;
2399 static int readset_n
= 0;
2401 // main loop - gets packets on tun or udp and processes them
2402 static void mainloop(void)
2407 clockt next_cluster_ping
= 0; // send initial ping immediately
2409 LOG(4, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2410 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2413 FD_SET(udpfd
, &readset
);
2414 FD_SET(tunfd
, &readset
);
2415 FD_SET(controlfd
, &readset
);
2416 FD_SET(clifd
, &readset
);
2417 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2419 if (tunfd
> readset_n
) readset_n
= tunfd
;
2420 if (controlfd
> readset_n
) readset_n
= controlfd
;
2421 if (clifd
> readset_n
) readset_n
= clifd
;
2422 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2424 while (!main_quit
|| still_busy())
2430 int bgp_set
[BGP_NUM_PEERS
];
2434 if (config
->reload_config
)
2436 // Update the config state based on config settings
2440 memcpy(&r
, &readset
, sizeof(fd_set
));
2442 to
.tv_usec
= 100000; // 1/10th of a second.
2446 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2448 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2451 FD_SET(bgp_peers
[i
].sock
, &r
);
2452 if (bgp_peers
[i
].sock
> n
)
2453 n
= bgp_peers
[i
].sock
;
2458 FD_SET(bgp_peers
[i
].sock
, &w
);
2459 if (bgp_peers
[i
].sock
> n
)
2460 n
= bgp_peers
[i
].sock
;
2464 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2466 n
= select(n
+ 1, &r
, 0, 0, &to
);
2469 STAT(select_called
);
2474 if (errno
== EINTR
||
2475 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2478 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2484 struct sockaddr_in addr
;
2488 int cluster_pkts
= 0;
2491 if (FD_ISSET(controlfd
, &r
))
2493 alen
= sizeof(addr
);
2494 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
, alen
);
2499 if (config
->cluster_iam_master
)
2501 for (i
= 0; i
< config
->num_radfds
; i
++)
2503 if (FD_ISSET(radfds
[i
], &r
))
2505 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2512 if (FD_ISSET(clifd
, &r
))
2516 alen
= sizeof(addr
);
2517 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
2523 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
2529 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2531 int isr
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0;
2532 int isw
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0;
2533 bgp_process(&bgp_peers
[i
], isr
, isw
);
2539 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
2542 if (FD_ISSET(udpfd
, &r
))
2544 alen
= sizeof(addr
);
2545 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
2547 processudp(buf
, s
, &addr
);
2558 if (FD_ISSET(tunfd
, &r
))
2560 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
2573 if (FD_ISSET(cluster_sockfd
, &r
))
2575 alen
= sizeof(addr
);
2576 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
2578 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
2583 FD_CLR(cluster_sockfd
, &r
);
2589 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
2590 STAT(multi_read_used
);
2592 if (c
>= config
->multi_read_count
)
2594 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
2595 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
2597 STAT(multi_read_exceeded
);
2602 // Runs on every machine (master and slaves).
2603 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
2605 // Check to see which of the cluster is still alive..
2607 cluster_send_ping(basetime
); // Only does anything if we're a slave
2608 cluster_check_master(); // ditto.
2610 cluster_heartbeat(); // Only does anything if we're a master.
2611 cluster_check_slaves(); // ditto.
2613 master_update_counts(); // If we're a slave, send our byte counters to our master.
2615 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
2616 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
2618 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
2621 if (!config
->cluster_iam_master
)
2624 // Run token bucket filtering queue..
2625 // Only run it every 1/10th of a second.
2627 static clockt last_run
= 0;
2628 if (last_run
!= TIME
)
2635 // Handle timeouts, retries etc.
2637 static double last_clean
= 0;
2641 TIME
= now(&this_clean
);
2642 diff
= this_clean
- last_clean
;
2644 // Run during idle time (after we've handled
2645 // all incoming packets) or every 1/10th sec
2646 if (!more
|| diff
> 0.1)
2648 regular_cleanups(diff
);
2649 last_clean
= this_clean
;
2653 if (*config
->accounting_dir
)
2655 static clockt next_acct
= 0;
2656 static clockt next_shut_acct
= 0;
2658 if (next_acct
<= TIME
)
2660 // Dump accounting data
2661 next_acct
= TIME
+ ACCT_TIME
;
2662 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2665 else if (next_shut_acct
<= TIME
)
2667 // Dump accounting data for shutdown sessions
2668 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2675 // Are we the master and shutting down??
2676 if (config
->cluster_iam_master
)
2677 cluster_heartbeat(); // Flush any queued changes..
2679 // Ok. Notify everyone we're shutting down. If we're
2680 // the master, this will force an election.
2681 cluster_send_ping(0);
2684 // Important!!! We MUST not process any packets past this point!
2685 LOG(1, 0, 0, "Clean shutdown complete\n");
2688 static void stripdomain(char *host
)
2692 if ((p
= strchr(host
, '.')))
2698 FILE *resolv
= fopen("/etc/resolv.conf", "r");
2704 while (fgets(buf
, sizeof(buf
), resolv
))
2706 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
2709 if (!isspace(buf
[6]))
2713 while (isspace(*b
)) b
++;
2718 while (*b
&& !isspace(*b
)) b
++;
2720 if (buf
[0] == 'd') // domain is canonical
2726 // first search line
2729 // hold, may be subsequent domain line
2730 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
2741 int hl
= strlen(host
);
2742 int dl
= strlen(domain
);
2743 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
2744 host
[hl
-dl
- 1] = 0;
2748 *p
= 0; // everything after first dot
2753 // Init data structures
2754 static void initdata(int optdebug
, char *optconfig
)
2758 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
2760 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
2763 if (!(config
= shared_malloc(sizeof(configt
))))
2765 LOG(0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2768 memset(config
, 0, sizeof(configt
));
2769 time(&config
->start_time
);
2770 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
2771 config
->debug
= optdebug
;
2772 config
->num_tbfs
= MAXTBFS
;
2773 config
->rl_rate
= 28; // 28kbps
2774 config
->cluster_master_min_adv
= 1;
2776 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
2778 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
2781 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
2783 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
2787 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
2789 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
2793 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
2795 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
2799 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
2801 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
2805 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
2807 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
2810 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
2813 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2815 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2818 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2821 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2823 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2826 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2828 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2830 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2833 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2835 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2836 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2837 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2838 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2840 // Put all the sessions on the free list marked as undefined.
2841 for (i
= 1; i
< MAXSESSION
; i
++)
2843 session
[i
].next
= i
+ 1;
2844 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2846 session
[MAXSESSION
- 1].next
= 0;
2849 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2850 for (i
= 1; i
< MAXTUNNEL
; i
++)
2851 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2855 // Grab my hostname unless it's been specified
2856 gethostname(hostname
, sizeof(hostname
));
2857 stripdomain(hostname
);
2860 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2863 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2865 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2871 static int assign_ip_address(sessionidt s
)
2875 time_t best_time
= time_now
;
2876 char *u
= session
[s
].user
;
2880 CSTAT(call_assign_ip_address
);
2882 for (i
= 1; i
< ip_pool_size
; i
++)
2884 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2887 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2894 if (ip_address_pool
[i
].last
< best_time
)
2897 if (!(best_time
= ip_address_pool
[i
].last
))
2898 break; // never used, grab this one
2904 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2908 session
[s
].ip
= ip_address_pool
[best
].address
;
2909 session
[s
].ip_pool_index
= best
;
2910 ip_address_pool
[best
].assigned
= 1;
2911 ip_address_pool
[best
].last
= time_now
;
2912 ip_address_pool
[best
].session
= s
;
2913 if (session
[s
].walled_garden
)
2914 /* Don't track addresses of users in walled garden (note: this
2915 means that their address isn't "sticky" even if they get
2917 ip_address_pool
[best
].user
[0] = 0;
2919 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2922 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
2923 reuse
? "Reusing" : "Allocating", best
);
2928 static void free_ip_address(sessionidt s
)
2930 int i
= session
[s
].ip_pool_index
;
2933 CSTAT(call_free_ip_address
);
2936 return; // what the?
2938 if (i
< 0) // Is this actually part of the ip pool?
2942 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2944 ip_address_pool
[i
].assigned
= 0;
2945 ip_address_pool
[i
].session
= 0;
2946 ip_address_pool
[i
].last
= time_now
;
2950 // Fsck the address pool against the session table.
2951 // Normally only called when we become a master.
2953 // This isn't perfect: We aren't keep tracking of which
2954 // users used to have an IP address.
2956 void rebuild_address_pool(void)
2961 // Zero the IP pool allocation, and build
2962 // a map from IP address to pool index.
2963 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2965 ip_address_pool
[i
].assigned
= 0;
2966 ip_address_pool
[i
].session
= 0;
2967 if (!ip_address_pool
[i
].address
)
2970 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2973 for (i
= 0; i
< MAXSESSION
; ++i
)
2976 if (!(session
[i
].opened
&& session
[i
].ip
))
2978 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2980 if (session
[i
].ip_pool_index
< 0)
2982 // Not allocated out of the pool.
2983 if (ipid
< 1) // Not found in the pool either? good.
2986 LOG(0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2987 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
2989 // Fall through and process it as part of the pool.
2993 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2995 LOG(0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2997 session
[i
].ip_pool_index
= ipid
;
3001 ip_address_pool
[ipid
].assigned
= 1;
3002 ip_address_pool
[ipid
].session
= i
;
3003 ip_address_pool
[ipid
].last
= time_now
;
3004 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
3005 session
[i
].ip_pool_index
= ipid
;
3006 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
3011 // Fix the address pool to match a changed session.
3012 // (usually when the master sends us an update).
3013 static void fix_address_pool(int sid
)
3017 ipid
= session
[sid
].ip_pool_index
;
3019 if (ipid
> ip_pool_size
)
3020 return; // Ignore it. rebuild_address_pool will fix it up.
3022 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
3023 return; // Just ignore it. rebuild_address_pool will take care of it.
3025 ip_address_pool
[ipid
].assigned
= 1;
3026 ip_address_pool
[ipid
].session
= sid
;
3027 ip_address_pool
[ipid
].last
= time_now
;
3028 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
3032 // Add a block of addresses to the IP pool to hand out.
3034 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
3038 mask
= 0xffffffff; // Host route only.
3042 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
3045 for (i
= addr
;(i
& mask
) == addr
; ++i
)
3047 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
3048 continue; // Skip 0 and broadcast addresses.
3050 ip_address_pool
[ip_pool_size
].address
= i
;
3051 ip_address_pool
[ip_pool_size
].assigned
= 0;
3053 if (ip_pool_size
>= MAXIPPOOL
)
3055 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
3061 // Initialize the IP address pool
3062 static void initippool()
3067 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
3069 if (!(f
= fopen(IPPOOLFILE
, "r")))
3071 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
3075 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
3078 buf
[4095] = 0; // Force it to be zero terminated/
3080 if (*buf
== '#' || *buf
== '\n')
3081 continue; // Skip comments / blank lines
3082 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
3083 if ((p
= (char *)strchr(buf
, ':')))
3087 src
= inet_addr(buf
);
3088 if (src
== INADDR_NONE
)
3090 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
3093 // This entry is for a specific IP only
3094 if (src
!= config
->bind_address
)
3099 if ((p
= (char *)strchr(pool
, '/')))
3103 in_addr_t start
= 0, mask
= 0;
3105 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
3107 if (!*p
|| !(numbits
= atoi(p
)))
3109 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
3112 start
= ntohl(inet_addr(pool
));
3113 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
3115 // Add a static route for this pool
3116 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
3117 fmtaddr(htonl(start
), 0), 32 + mask
);
3119 routeset(0, start
, mask
, 0, 1);
3121 add_to_ip_pool(start
, mask
);
3125 // It's a single ip address
3126 add_to_ip_pool(inet_addr(pool
), 0);
3130 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
3133 void snoop_send_packet(char *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
3135 struct sockaddr_in snoop_addr
= {0};
3136 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
3139 snoop_addr
.sin_family
= AF_INET
;
3140 snoop_addr
.sin_addr
.s_addr
= destination
;
3141 snoop_addr
.sin_port
= ntohs(port
);
3143 LOG(5, 0, 0, "Snooping %d byte packet to %s:%d\n", size
,
3144 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
3145 htons(snoop_addr
.sin_port
));
3147 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
3148 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
3150 STAT(packets_snooped
);
3153 static int dump_session(FILE **f
, sessiont
*s
)
3155 if (!s
->opened
|| !s
->ip
|| !(s
->cin
|| s
->cout
) || !*s
->user
|| s
->walled_garden
)
3160 char filename
[1024];
3162 time_t now
= time(NULL
);
3164 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
3165 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
3167 if (!(*f
= fopen(filename
, "w")))
3169 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
3173 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
3174 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
3178 "# format: username ip qos uptxoctets downrxoctets\n",
3184 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
3185 fprintf(*f
, "%s %s %d %u %u\n",
3186 s
->user
, // username
3187 fmtaddr(htonl(s
->ip
), 0), // ip
3188 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
3189 (uint32_t) s
->cin
, // uptxoctets
3190 (uint32_t) s
->cout
); // downrxoctets
3192 s
->pin
= s
->cin
= 0;
3193 s
->pout
= s
->cout
= 0;
3198 static void dump_acct_info(int all
)
3204 CSTAT(call_dump_acct_info
);
3208 for (i
= 0; i
< shut_acct_n
; i
++)
3209 dump_session(&f
, &shut_acct
[i
]);
3215 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3216 dump_session(&f
, &session
[i
]);
3223 int main(int argc
, char *argv
[])
3227 char *optconfig
= CONFIGFILE
;
3229 time(&basetime
); // start clock
3232 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
3237 if (fork()) exit(0);
3239 freopen("/dev/null", "r", stdin
);
3240 freopen("/dev/null", "w", stdout
);
3241 freopen("/dev/null", "w", stderr
);
3250 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
3253 printf("Args are:\n"
3254 "\t-d\t\tDetach from terminal\n"
3255 "\t-c <file>\tConfig file\n"
3256 "\t-h <hostname>\tForce hostname\n"
3264 // Start the timer routine off
3266 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3267 signal(SIGALRM
, sigalrm_handler
);
3268 siginterrupt(SIGALRM
, 0);
3271 initdata(optdebug
, optconfig
);
3275 init_tbf(config
->num_tbfs
);
3277 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
3278 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005 Optus Internet Engineering\n");
3279 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3282 rlim
.rlim_cur
= RLIM_INFINITY
;
3283 rlim
.rlim_max
= RLIM_INFINITY
;
3284 // Remove the maximum core size
3285 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
3286 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
3288 // Make core dumps go to /tmp
3292 if (config
->scheduler_fifo
)
3295 struct sched_param params
= {0};
3296 params
.sched_priority
= 1;
3298 if (get_nprocs() < 2)
3300 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3301 config
->scheduler_fifo
= 0;
3305 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3307 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3311 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3312 config
->scheduler_fifo
= 0;
3317 /* Set up the cluster communications port. */
3318 if (cluster_init() < 0)
3322 signal(SIGPIPE
, SIG_IGN
);
3323 bgp_setup(config
->as_number
);
3324 bgp_add_route(config
->bind_address
, 0xffffffff);
3325 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3327 if (config
->neighbour
[i
].name
[0])
3328 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3329 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3330 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3335 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3343 signal(SIGHUP
, sighup_handler
);
3344 signal(SIGTERM
, sigterm_handler
);
3345 signal(SIGINT
, sigterm_handler
);
3346 signal(SIGQUIT
, sigquit_handler
);
3347 signal(SIGCHLD
, sigchild_handler
);
3349 // Prevent us from getting paged out
3350 if (config
->lock_pages
)
3352 if (!mlockall(MCL_CURRENT
))
3353 LOG(1, 0, 0, "Locking pages into memory\n");
3355 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3360 // Drop privileges here
3361 if (config
->target_uid
> 0 && geteuid() == 0)
3362 setuid(config
->target_uid
);
3366 /* remove plugins (so cleanup code gets run) */
3369 // Remove the PID file if we wrote it
3370 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3371 unlink(config
->pid_file
);
3373 /* kill CLI children */
3374 signal(SIGTERM
, SIG_IGN
);
3379 static void sighup_handler(int sig
)
3381 if (log_stream
&& log_stream
!= stderr
)
3390 static void sigalrm_handler(int sig
)
3392 // Log current traffic stats
3394 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3395 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3396 (udp_rx
/ 1024.0 / 1024.0 * 8),
3397 (eth_tx
/ 1024.0 / 1024.0 * 8),
3398 (eth_rx
/ 1024.0 / 1024.0 * 8),
3399 (udp_tx
/ 1024.0 / 1024.0 * 8),
3400 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3401 udp_rx_pkt
, eth_rx_pkt
);
3403 udp_tx
= udp_rx
= 0;
3404 udp_rx_pkt
= eth_rx_pkt
= 0;
3405 eth_tx
= eth_rx
= 0;
3407 if (config
->dump_speed
)
3408 printf("%s\n", config
->bandwidth
);
3410 // Update the internal time counter
3412 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3417 struct param_timer p
= { time_now
};
3418 run_plugins(PLUGIN_TIMER
, &p
);
3423 static void sigterm_handler(int sig
)
3425 LOG(1, 0, 0, "Shutting down cleanly\n");
3426 if (config
->save_state
)
3432 static void sigquit_handler(int sig
)
3436 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3438 if (config
->cluster_iam_master
)
3440 for (i
= 1; i
< MAXSESSION
; i
++)
3442 if (session
[i
].opened
)
3443 sessionkill(i
, "L2TPNS Closing");
3445 for (i
= 1; i
< MAXTUNNEL
; i
++)
3447 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3448 tunnelshutdown(i
, "L2TPNS Closing");
3455 static void sigchild_handler(int sig
)
3457 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3461 static void read_state()
3467 char magic
[sizeof(DUMP_MAGIC
) - 1];
3470 if (!config
->save_state
)
3476 if (stat(STATEFILE
, &sb
) < 0)
3482 if (sb
.st_mtime
< (time(NULL
) - 60))
3484 LOG(0, 0, 0, "State file is too old to read, ignoring\n");
3489 f
= fopen(STATEFILE
, "r");
3494 LOG(0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3498 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3500 LOG(0, 0, 0, "Bad state file magic\n");
3504 LOG(1, 0, 0, "Reading state information\n");
3505 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3507 LOG(0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3511 if (buf
[0] > ip_pool_size
)
3513 LOG(0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3517 LOG(2, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3518 for (i
= 0; i
< buf
[0]; i
++)
3520 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3522 LOG(0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3526 if (itmp
.address
!= ip_address_pool
[i
].address
)
3528 LOG(0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3532 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3535 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3537 LOG(0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3541 LOG(2, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3542 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3544 LOG(0, 0, 0, "Error reading tunnel data from state file\n");
3548 for (i
= 0; i
< MAXTUNNEL
; i
++)
3550 tunnel
[i
].controlc
= 0;
3551 tunnel
[i
].controls
= NULL
;
3552 tunnel
[i
].controle
= NULL
;
3553 if (*tunnel
[i
].hostname
)
3554 LOG(3, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3557 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3559 LOG(0, 0, 0, "Error/mismatch reading session header from state file\n");
3563 LOG(2, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3564 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3566 LOG(0, 0, 0, "Error reading session data from state file\n");
3570 for (i
= 0; i
< MAXSESSION
; i
++)
3572 session
[i
].tbf_in
= 0;
3573 session
[i
].tbf_out
= 0;
3574 if (session
[i
].opened
)
3576 LOG(2, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3578 sessionsetup(session
[i
].tunnel
, i
);
3583 LOG(0, 0, 0, "Loaded saved state information\n");
3586 static void dump_state()
3591 if (!config
->save_state
)
3596 if (!(f
= fopen(STATEFILE
, "w")))
3599 LOG(1, 0, 0, "Dumping state information\n");
3601 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3604 LOG(2, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3605 buf
[0] = ip_pool_size
;
3606 buf
[1] = sizeof(ippoolt
);
3607 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3609 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3612 LOG(2, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3614 buf
[1] = sizeof(tunnelt
);
3615 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3617 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3620 LOG(2, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3621 buf
[0] = MAXSESSION
;
3622 buf
[1] = sizeof(sessiont
);
3623 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3625 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3633 LOG(0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3637 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
)
3640 *challenge_response
= NULL
;
3642 if (!*config
->l2tpsecret
)
3644 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3648 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
3650 *challenge_response
= (char *)calloc(17, 1);
3653 MD5Update(&ctx
, &id
, 1);
3654 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3655 MD5Update(&ctx
, challenge
, challenge_length
);
3656 MD5Final(*challenge_response
, &ctx
);
3661 static int facility_value(char *name
)
3664 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3666 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3667 return facilitynames
[i
].c_val
;
3672 static void update_config()
3675 static int timeout
= 0;
3676 static int interval
= 0;
3686 if (*config
->log_filename
)
3688 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3690 char *p
= config
->log_filename
+ 7;
3693 openlog("l2tpns", LOG_PID
, facility_value(p
));
3697 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3699 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3701 fseek(log_stream
, 0, SEEK_END
);
3702 setbuf(log_stream
, NULL
);
3706 log_stream
= stderr
;
3707 setbuf(log_stream
, NULL
);
3713 log_stream
= stderr
;
3714 setbuf(log_stream
, NULL
);
3719 config
->numradiusservers
= 0;
3720 for (i
= 0; i
< MAXRADSERVER
; i
++)
3721 if (config
->radiusserver
[i
])
3723 config
->numradiusservers
++;
3724 // Set radius port: if not set, take the port from the
3725 // first radius server. For the first radius server,
3726 // take the #defined default value from l2tpns.h
3728 // test twice, In case someone works with
3729 // a secondary radius server without defining
3730 // a primary one, this will work even then.
3731 if (i
>0 && !config
->radiusport
[i
])
3732 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3733 if (!config
->radiusport
[i
])
3734 config
->radiusport
[i
] = RADPORT
;
3737 if (!config
->numradiusservers
)
3738 LOG(0, 0, 0, "No RADIUS servers defined!\n");
3740 config
->num_radfds
= 1 << RADIUS_SHIFT
;
3743 for (i
= 0; i
< MAXPLUGINS
; i
++)
3745 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3748 if (*config
->plugins
[i
])
3751 add_plugin(config
->plugins
[i
]);
3753 else if (*config
->old_plugins
[i
])
3756 remove_plugin(config
->old_plugins
[i
]);
3759 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3760 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3761 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3762 if (!*config
->cluster_interface
)
3763 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3765 if (!config
->cluster_hb_interval
)
3766 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3768 if (!config
->cluster_hb_timeout
)
3769 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3771 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3773 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3774 // late, ensure we're sufficiently larger than that
3775 int t
= 4 * config
->cluster_hb_interval
+ 11;
3777 if (config
->cluster_hb_timeout
< t
)
3779 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3780 config
->cluster_hb_timeout
= t
;
3783 // Push timing changes to the slaves immediately if we're the master
3784 if (config
->cluster_iam_master
)
3785 cluster_heartbeat();
3787 interval
= config
->cluster_hb_interval
;
3788 timeout
= config
->cluster_hb_timeout
;
3792 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3795 if ((f
= fopen(config
->pid_file
, "w")))
3797 fprintf(f
, "%d\n", getpid());
3799 config
->wrote_pid
= 1;
3803 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3807 config
->reload_config
= 0;
3810 static void read_config_file()
3814 if (!config
->config_file
) return;
3815 if (!(f
= fopen(config
->config_file
, "r")))
3817 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3821 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
3823 LOG(3, 0, 0, "Done reading config file\n");
3828 int sessionsetup(tunnelidt t
, sessionidt s
)
3830 // A session now exists, set it up
3836 CSTAT(call_sessionsetup
);
3838 LOG(3, s
, t
, "Doing session setup for session\n");
3842 assign_ip_address(s
);
3845 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3846 sessionshutdown(s
, "No IP addresses available");
3849 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
3850 fmtaddr(htonl(session
[s
].ip
), 0));
3854 // Make sure this is right
3855 session
[s
].tunnel
= t
;
3857 // zap old sessions with same IP and/or username
3858 // Don't kill gardened sessions - doing so leads to a DoS
3859 // from someone who doesn't need to know the password
3862 user
= session
[s
].user
;
3863 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3865 if (i
== s
) continue;
3866 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3867 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3868 sessionkill(i
, "Duplicate session for users");
3875 // Add the route for this session.
3876 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3878 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
3879 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
3882 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
3885 // Static IPs need to be routed if not already
3886 // convered by a Framed-Route. Anything else is part
3887 // of the IP address pool and is already routed, it
3888 // just needs to be added to the IP cache.
3889 if (session
[s
].ip_pool_index
== -1) // static ip
3891 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
3894 cache_ipmap(session
[s
].ip
, s
);
3897 if (!session
[s
].unique_id
)
3899 // did this session just finish radius?
3900 LOG(3, s
, t
, "Sending initial IPCP to client\n");
3902 session
[s
].unique_id
= ++last_id
;
3905 // Run the plugin's against this new session.
3907 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3908 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3911 // Allocate TBFs if throttled
3912 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3913 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3915 session
[s
].last_packet
= time_now
;
3917 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
3918 fmtaddr(htonl(session
[s
].ip
), 0),
3919 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
3921 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3923 return 1; // RADIUS OK and IP allocated, done...
3927 // This session just got dropped on us by the master or something.
3928 // Make sure our tables up up to date...
3930 int load_session(sessionidt s
, sessiont
*new)
3936 if (new->ip_pool_index
>= MAXIPPOOL
||
3937 new->tunnel
>= MAXTUNNEL
)
3939 LOG(0, s
, 0, "Strange session update received!\n");
3940 // FIXME! What to do here?
3945 // Ok. All sanity checks passed. Now we're committed to
3946 // loading the new session.
3949 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3951 // See if routes/ip cache need updating
3952 if (new->ip
!= session
[s
].ip
)
3955 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3956 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
3957 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
3965 // remove old routes...
3966 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3968 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
3969 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
3972 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
3978 if (session
[s
].ip_pool_index
== -1) // static IP
3980 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
3982 else // It's part of the IP pool, remove it manually.
3983 uncache_ipmap(session
[s
].ip
);
3988 // add new routes...
3989 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
3991 if ((new->ip
& new->route
[i
].mask
) ==
3992 (new->route
[i
].ip
& new->route
[i
].mask
))
3995 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
4001 // If there's a new one, add it.
4002 if (new->ip_pool_index
== -1)
4004 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
4007 cache_ipmap(new->ip
, s
);
4012 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
4014 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %d\n", (int) new->filter_in
);
4018 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
4020 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %d\n", (int) new->filter_out
);
4021 new->filter_out
= 0;
4024 if (new->filter_in
!= session
[s
].filter_in
)
4026 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
4027 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
4030 if (new->filter_out
!= session
[s
].filter_out
)
4032 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
4033 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
4036 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
4037 // for walking the sessions to forward byte counts to the master.
4038 config
->cluster_highest_sessionid
= s
;
4040 // TEMP: old session struct used a uint32_t to define the throttle
4041 // speed for both up/down, new uses a uint16_t for each. Deal with
4042 // sessions from an old master for migration.
4043 if (new->throttle_out
== 0 && new->tbf_out
)
4044 new->throttle_out
= new->throttle_in
;
4046 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
4048 // Do fixups into address pool.
4049 if (new->ip_pool_index
!= -1)
4050 fix_address_pool(s
);
4055 static void initplugins()
4059 loaded_plugins
= ll_init();
4060 // Initialize the plugins to nothing
4061 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
4062 plugins
[i
] = ll_init();
4065 static void *open_plugin(char *plugin_name
, int load
)
4067 char path
[256] = "";
4069 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
4070 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
4071 return dlopen(path
, RTLD_NOW
);
4074 // plugin callback to get a config value
4075 static void *getconfig(char *key
, enum config_typet type
)
4079 for (i
= 0; config_values
[i
].key
; i
++)
4081 if (!strcmp(config_values
[i
].key
, key
))
4083 if (config_values
[i
].type
== type
)
4084 return ((void *) config
) + config_values
[i
].offset
;
4086 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
4087 key
, type
, config_values
[i
].type
);
4093 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
4097 static int add_plugin(char *plugin_name
)
4099 static struct pluginfuncs funcs
= {
4104 sessiontbysessionidt
,
4105 sessionidtbysessiont
,
4111 cluster_send_session
,
4114 void *p
= open_plugin(plugin_name
, 1);
4115 int (*initfunc
)(struct pluginfuncs
*);
4120 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
4124 if (ll_contains(loaded_plugins
, p
))
4127 return 0; // already loaded
4131 int *v
= dlsym(p
, "plugin_api_version");
4132 if (!v
|| *v
!= PLUGIN_API_VERSION
)
4134 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
4140 if ((initfunc
= dlsym(p
, "plugin_init")))
4142 if (!initfunc(&funcs
))
4144 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
4150 ll_push(loaded_plugins
, p
);
4152 for (i
= 0; i
< max_plugin_functions
; i
++)
4155 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4157 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
4158 ll_push(plugins
[i
], x
);
4162 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
4166 static void run_plugin_done(void *plugin
)
4168 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
4174 static int remove_plugin(char *plugin_name
)
4176 void *p
= open_plugin(plugin_name
, 0);
4182 if (ll_contains(loaded_plugins
, p
))
4185 for (i
= 0; i
< max_plugin_functions
; i
++)
4188 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4189 ll_delete(plugins
[i
], x
);
4192 ll_delete(loaded_plugins
, p
);
4198 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
4202 int run_plugins(int plugin_type
, void *data
)
4204 int (*func
)(void *data
);
4206 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
4207 return PLUGIN_RET_ERROR
;
4209 ll_reset(plugins
[plugin_type
]);
4210 while ((func
= ll_next(plugins
[plugin_type
])))
4214 if (r
!= PLUGIN_RET_OK
)
4215 return r
; // stop here
4218 return PLUGIN_RET_OK
;
4221 static void plugins_done()
4225 ll_reset(loaded_plugins
);
4226 while ((p
= ll_next(loaded_plugins
)))
4230 static void processcontrol(uint8_t * buf
, int len
, struct sockaddr_in
*addr
, int alen
)
4232 struct nsctl request
;
4233 struct nsctl response
;
4234 int type
= unpack_control(&request
, buf
, len
);
4238 if (log_stream
&& config
->debug
>= 4)
4242 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4243 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
4247 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4248 dump_control(&request
, log_stream
);
4254 case NSCTL_REQ_LOAD
:
4255 if (request
.argc
!= 1)
4257 response
.type
= NSCTL_RES_ERR
;
4259 response
.argv
[0] = "name of plugin required";
4261 else if ((r
= add_plugin(request
.argv
[0])) < 1)
4263 response
.type
= NSCTL_RES_ERR
;
4265 response
.argv
[0] = !r
4266 ? "plugin already loaded"
4267 : "error loading plugin";
4271 response
.type
= NSCTL_RES_OK
;
4277 case NSCTL_REQ_UNLOAD
:
4278 if (request
.argc
!= 1)
4280 response
.type
= NSCTL_RES_ERR
;
4282 response
.argv
[0] = "name of plugin required";
4284 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
4286 response
.type
= NSCTL_RES_ERR
;
4288 response
.argv
[0] = !r
4289 ? "plugin not loaded"
4290 : "plugin not found";
4294 response
.type
= NSCTL_RES_OK
;
4300 case NSCTL_REQ_HELP
:
4301 response
.type
= NSCTL_RES_OK
;
4304 ll_reset(loaded_plugins
);
4305 while ((p
= ll_next(loaded_plugins
)))
4307 char **help
= dlsym(p
, "plugin_control_help");
4308 while (response
.argc
< 0xff && help
&& *help
)
4309 response
.argv
[response
.argc
++] = *help
++;
4314 case NSCTL_REQ_CONTROL
:
4316 struct param_control param
= {
4317 config
->cluster_iam_master
,
4324 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4326 if (r
== PLUGIN_RET_ERROR
)
4328 response
.type
= NSCTL_RES_ERR
;
4330 response
.argv
[0] = param
.additional
4332 : "error returned by plugin";
4334 else if (r
== PLUGIN_RET_NOTMASTER
)
4336 static char msg
[] = "must be run on master: 000.000.000.000";
4338 response
.type
= NSCTL_RES_ERR
;
4340 if (config
->cluster_master_address
)
4342 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
4343 response
.argv
[0] = msg
;
4347 response
.argv
[0] = "must be run on master: none elected";
4350 else if (!(param
.response
& NSCTL_RESPONSE
))
4352 response
.type
= NSCTL_RES_ERR
;
4354 response
.argv
[0] = param
.response
4355 ? "unrecognised response value from plugin"
4356 : "unhandled action";
4360 response
.type
= param
.response
;
4362 if (param
.additional
)
4365 response
.argv
[0] = param
.additional
;
4373 response
.type
= NSCTL_RES_ERR
;
4375 response
.argv
[0] = "error unpacking control packet";
4378 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4381 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4385 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4388 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4389 if (log_stream
&& config
->debug
>= 4)
4391 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4392 dump_control(&response
, log_stream
);
4396 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4397 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
4402 static tunnelidt
new_tunnel()
4405 for (i
= 1; i
< MAXTUNNEL
; i
++)
4407 if (tunnel
[i
].state
== TUNNELFREE
)
4409 LOG(4, 0, i
, "Assigning tunnel ID %d\n", i
);
4410 if (i
> config
->cluster_highest_tunnelid
)
4411 config
->cluster_highest_tunnelid
= i
;
4415 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4420 // We're becoming the master. Do any required setup..
4422 // This is principally telling all the plugins that we're
4423 // now a master, and telling them about all the sessions
4424 // that are active too..
4426 void become_master(void)
4429 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4431 // running a bunch of iptables commands is slow and can cause
4432 // the master to drop tunnels on takeover--kludge around the
4433 // problem by forking for the moment (note: race)
4434 if (!fork_and_close())
4436 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4438 if (!session
[s
].opened
) // Not an in-use session.
4441 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4447 for (i
= 0; i
< config
->num_radfds
; i
++)
4449 FD_SET(radfds
[i
], &readset
);
4450 if (radfds
[i
] > readset_n
)
4451 readset_n
= radfds
[i
];
4455 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4461 if (CLI_HELP_REQUESTED
)
4462 return CLI_HELP_NO_ARGS
;
4465 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4467 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4470 if (!session
[s
].opened
)
4473 idle
= time_now
- session
[s
].last_packet
;
4474 idle
/= 5 ; // In multiples of 5 seconds.
4484 for (i
= 0; i
< 63; ++i
)
4486 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4488 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4489 cli_print(cli
, "%d total sessions open.", count
);
4493 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4499 if (CLI_HELP_REQUESTED
)
4500 return CLI_HELP_NO_ARGS
;
4503 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4505 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4508 if (!session
[s
].opened
)
4511 d
= time_now
- session
[s
].opened
;
4514 while (d
> 1 && open
< 32)
4524 for (i
= 0; i
< 30; ++i
)
4526 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4529 cli_print(cli
, "%d total sessions open.", count
);
4535 * This unencodes the AVP using the L2TP CHAP secret and the
4536 * previously stored random vector. It replaces the hidden data with
4537 * the cleartext data and returns the length of the cleartext data
4538 * (including the AVP "header" of 6 bytes).
4540 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4542 static int unhide_avp(uint8_t *avp
, tunnelidt t
, sessionidt s
, uint16_t length
)
4547 uint8_t working_vector
[16];
4548 uint16_t hidden_length
;
4553 // Find the AVP type.
4554 type
[0] = *(avp
+ 4);
4555 type
[1] = *(avp
+ 5);
4557 // Line up with the hidden data
4558 cursor
= output
= avp
+ 6;
4560 // Compute initial pad
4562 MD5Update(&ctx
, type
, 2);
4563 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4564 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4565 MD5Final(digest
, &ctx
);
4567 // Get hidden length
4568 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4570 // Keep these for later use
4571 working_vector
[0] = *cursor
;
4572 working_vector
[1] = *(cursor
+ 1);
4575 if (hidden_length
> length
- 8)
4577 LOG(1, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4581 /* Decrypt remainder */
4583 todo
= hidden_length
;
4586 working_vector
[done
] = *cursor
;
4587 *output
= digest
[done
] ^ *cursor
;
4592 if (done
== 16 && todo
)
4594 // Compute new digest
4597 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4598 MD5Update(&ctx
, &working_vector
, 16);
4599 MD5Final(digest
, &ctx
);
4603 return hidden_length
+ 6;
4606 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
4610 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
4611 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
4612 case FILTER_PORT_OP_GT
: return port
> p
->port
;
4613 case FILTER_PORT_OP_LT
: return port
< p
->port
;
4614 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
4620 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
4624 case FILTER_FLAG_OP_ANY
:
4625 return (flags
& sflags
) || (~flags
& cflags
);
4627 case FILTER_FLAG_OP_ALL
:
4628 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
4630 case FILTER_FLAG_OP_EST
:
4631 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
4637 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
4639 uint16_t frag_offset
;
4643 uint16_t src_port
= 0;
4644 uint16_t dst_port
= 0;
4646 ip_filter_rulet
*rule
;
4648 if (len
< 20) // up to end of destination address
4651 if ((*buf
>> 4) != 4) // IPv4
4654 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
4656 src_ip
= *(in_addr_t
*) (buf
+ 12);
4657 dst_ip
= *(in_addr_t
*) (buf
+ 16);
4659 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
4661 int l
= (buf
[0] & 0xf) * 4; // length of IP header
4662 if (len
< l
+ 4) // ports
4665 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
4666 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
4667 if (proto
== IPPROTO_TCP
)
4669 if (len
< l
+ 14) // flags
4672 flags
= buf
[l
+ 13] & 0x3f;
4676 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
4678 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
4681 if (rule
->src_wild
!= INADDR_BROADCAST
&&
4682 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
4685 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
4686 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
4691 if (!rule
->frag
|| rule
->action
== FILTER_ACTION_DENY
)
4699 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
4701 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
4704 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
4707 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
4708 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
4715 return rule
->action
== FILTER_ACTION_PERMIT
;