3 // Copyright (c) 2003, 2004 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.74 2004/12/18 01:20:05 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 static 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
, IPv4
),
99 CONFIG("secondary_dns", default_dns2
, IPv4
),
100 CONFIG("save_state", save_state
, BOOL
),
101 CONFIG("primary_radius", radiusserver
[0], IPv4
),
102 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
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
, IPv4
),
108 CONFIG("peer_address", peer_address
, IPv4
),
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("cleanup_interval", cleanup_interval
, INT
),
116 CONFIG("multi_read_count", multi_read_count
, INT
),
117 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
118 CONFIG("lock_pages", lock_pages
, BOOL
),
119 CONFIG("icmp_rate", icmp_rate
, INT
),
120 CONFIG("cluster_address", cluster_address
, IPv4
),
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
),
127 static char *plugin_functions
[] = {
134 "plugin_new_session",
135 "plugin_kill_session",
137 "plugin_radius_response",
138 "plugin_become_master",
139 "plugin_new_session_master",
142 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
144 // Counters for shutdown sessions
145 static sessiont shut_acct
[8192];
146 static sessionidt shut_acct_n
= 0;
148 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
149 sessiont
*session
= NULL
; // Array of session structures.
150 sessioncountt
*sess_count
= NULL
; // Array of partial per-session traffic counters.
151 radiust
*radius
= NULL
; // Array of radius structures.
152 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
153 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
154 static controlt
*controlfree
= 0;
155 struct Tstats
*_statistics
= NULL
;
157 struct Tringbuffer
*ringbuffer
= NULL
;
160 static void cache_ipmap(in_addr_t ip
, int s
);
161 static void uncache_ipmap(in_addr_t ip
);
162 static void free_ip_address(sessionidt s
);
163 static void dump_acct_info(int all
);
164 static void sighup_handler(int sig
);
165 static void sigalrm_handler(int sig
);
166 static void sigterm_handler(int sig
);
167 static void sigquit_handler(int sig
);
168 static void sigchild_handler(int sig
);
169 static void read_state(void);
170 static void dump_state(void);
171 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
);
172 static void update_config(void);
173 static void read_config_file(void);
174 static void initplugins(void);
175 static int add_plugin(char *plugin_name
);
176 static int remove_plugin(char *plugin_name
);
177 static void plugins_done(void);
178 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
);
179 static tunnelidt
new_tunnel(void);
180 static int unhide_avp(uint8_t *avp
, tunnelidt t
, sessionidt s
, uint16_t length
);
182 // return internal time (10ths since process startup)
183 static clockt
now(void)
187 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
190 // work out a retry time based on try number
191 // This is a straight bounded exponential backoff.
192 // Maximum re-try time is 32 seconds. (2^5).
193 clockt
backoff(uint8_t try)
195 if (try > 5) try = 5; // max backoff
196 return now() + 10 * (1 << try);
201 // Log a debug message. Typically called via the LOG macro
203 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
205 static char message
[65536] = {0};
206 static char message2
[65536] = {0};
212 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
213 ringbuffer
->tail
= 0;
214 if (ringbuffer
->tail
== ringbuffer
->head
)
215 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
216 ringbuffer
->head
= 0;
218 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
219 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
220 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
221 va_start(ap
, format
);
222 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
227 if (config
->debug
< level
) return;
229 va_start(ap
, format
);
232 vsnprintf(message2
, 65535, format
, ap
);
233 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
234 fprintf(log_stream
, "%s", message
);
238 vsnprintf(message2
, 65535, format
, ap
);
239 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
240 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
245 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
248 const uint8_t *d
= (const uint8_t *) data
;
250 if (config
->debug
< level
) return;
252 // No support for _log_hex to syslog
255 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
256 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
258 for (i
= 0; i
< maxsize
; )
260 fprintf(log_stream
, "%4X: ", i
);
261 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
263 fprintf(log_stream
, "%02X ", d
[j
]);
265 fputs(": ", log_stream
);
268 for (; j
< i
+ 16; j
++)
270 fputs(" ", log_stream
);
272 fputs(": ", log_stream
);
275 fputs(" ", log_stream
);
276 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
278 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
279 fputc(d
[j
], log_stream
);
281 fputc('.', log_stream
);
284 fputs(" ", log_stream
);
288 fputs("\n", log_stream
);
292 setbuf(log_stream
, NULL
);
299 // This adds it to the routing table, advertises it
300 // via BGP if enabled, and stuffs it into the
301 // 'sessionbyip' cache.
303 // 'ip' and 'mask' must be in _host_ order.
305 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
310 if (!mask
) mask
= 0xffffffff;
312 ip
&= mask
; // Force the ip to be the first one in the route.
314 memset(&r
, 0, sizeof(r
));
315 r
.rt_dev
= config
->tundevice
;
316 r
.rt_dst
.sa_family
= AF_INET
;
317 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
318 r
.rt_gateway
.sa_family
= AF_INET
;
319 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
320 r
.rt_genmask
.sa_family
= AF_INET
;
321 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
322 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
324 r
.rt_flags
|= RTF_GATEWAY
;
325 else if (mask
== 0xffffffff)
326 r
.rt_flags
|= RTF_HOST
;
328 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
329 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
330 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
332 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
333 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
337 bgp_add_route(htonl(ip
), htonl(mask
));
339 bgp_del_route(htonl(ip
), htonl(mask
));
342 // Add/Remove the IPs to the 'sessionbyip' cache.
343 // Note that we add the zero address in the case of
344 // a network route. Roll on CIDR.
346 // Note that 's == 0' implies this is the address pool.
347 // We still cache it here, because it will pre-fill
348 // the malloc'ed tree.
352 if (!add
) // Are we deleting a route?
353 s
= 0; // Caching the session as '0' is the same as uncaching.
355 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
361 // Set up TUN interface
362 static void inittun(void)
365 struct sockaddr_in sin
= {0};
366 memset(&ifr
, 0, sizeof(ifr
));
367 ifr
.ifr_flags
= IFF_TUN
;
369 tunfd
= open(TUNDEVICE
, O_RDWR
);
372 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
376 int flags
= fcntl(tunfd
, F_GETFL
, 0);
377 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
379 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
381 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
384 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
385 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
386 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
388 sin
.sin_family
= AF_INET
;
389 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
390 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
392 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
394 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
397 /* Bump up the qlen to deal with bursts from the network */
399 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
401 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
404 ifr
.ifr_flags
= IFF_UP
;
405 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
407 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
413 static void initudp(void)
416 struct sockaddr_in addr
;
419 memset(&addr
, 0, sizeof(addr
));
420 addr
.sin_family
= AF_INET
;
421 addr
.sin_port
= htons(L2TPPORT
);
422 addr
.sin_addr
.s_addr
= config
->bind_address
;
423 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
424 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
426 int flags
= fcntl(udpfd
, F_GETFL
, 0);
427 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
429 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
431 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
434 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
437 memset(&addr
, 0, sizeof(addr
));
438 addr
.sin_family
= AF_INET
;
439 addr
.sin_port
= htons(NSCTL_PORT
);
440 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
441 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
442 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
444 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
450 // Find session by IP, < 1 for not found
452 // Confusingly enough, this 'ip' must be
453 // in _network_ order. This being the common
454 // case when looking it up from IP packet headers.
456 // We actually use this cache for two things.
457 // #1. For used IP addresses, this maps to the
458 // session ID that it's used by.
459 // #2. For un-used IP addresses, this maps to the
460 // index into the pool table that contains that
464 static int lookup_ipmap(in_addr_t ip
)
466 uint8_t *a
= (uint8_t *) &ip
;
467 uint8_t **d
= (uint8_t **) ip_hash
;
469 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
470 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
471 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
473 return (int) (intptr_t) d
[(size_t) *a
];
476 sessionidt
sessionbyip(in_addr_t ip
)
478 int s
= lookup_ipmap(ip
);
479 CSTAT(call_sessionbyip
);
481 if (s
> 0 && s
< MAXSESSION
&& session
[s
].tunnel
)
482 return (sessionidt
) s
;
488 // Take an IP address in HOST byte order and
489 // add it to the sessionid by IP cache.
491 // (It's actually cached in network order)
493 static void cache_ipmap(in_addr_t ip
, int s
)
495 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
496 uint8_t *a
= (uint8_t *) &nip
;
497 uint8_t **d
= (uint8_t **) ip_hash
;
500 for (i
= 0; i
< 3; i
++)
502 if (!d
[(size_t) a
[i
]])
504 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof(void *))))
508 d
= (uint8_t **) d
[(size_t) a
[i
]];
511 d
[(size_t) a
[3]] = (uint8_t *) (intptr_t) s
;
514 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
517 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
518 // else a map to an ip pool index.
521 static void uncache_ipmap(in_addr_t ip
)
523 cache_ipmap(ip
, 0); // Assign it to the NULL session.
527 // CLI list to dump current ipcache.
529 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
531 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
535 if (CLI_HELP_REQUESTED
)
536 return CLI_HELP_NO_ARGS
;
538 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
540 for (i
= 0; i
< 256; ++i
)
545 for (j
= 0; j
< 256; ++j
)
550 for (k
= 0; k
< 256; ++k
)
555 for (l
= 0; l
< 256; ++l
)
559 cli_print(cli
, "%7d %d.%d.%d.%d", (int) (intptr_t) g
[l
], i
, j
, k
, l
);
565 cli_print(cli
, "%d entries in cache", count
);
570 // Find session by username, 0 for not found
571 // walled garden users aren't authenticated, so the username is
572 // reasonably useless. Ignore them to avoid incorrect actions
574 // This is VERY inefficent. Don't call it often. :)
576 sessionidt
sessionbyuser(char *username
)
579 CSTAT(call_sessionbyuser
);
581 for (s
= 1; s
< MAXSESSION
; ++s
)
583 if (session
[s
].walled_garden
)
584 continue; // Skip walled garden users.
586 if (!strncmp(session
[s
].user
, username
, 128))
590 return 0; // Not found.
593 void send_garp(in_addr_t ip
)
599 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
602 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
605 memset(&ifr
, 0, sizeof(ifr
));
606 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
607 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
609 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
613 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
614 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
616 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
621 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
624 // Find session by username, 0 for not found
625 static sessiont
*sessiontbysessionidt(sessionidt s
)
627 if (!s
|| s
> MAXSESSION
) return NULL
;
631 static sessionidt
sessionidtbysessiont(sessiont
*s
)
633 sessionidt val
= s
-session
;
634 if (s
< session
|| val
> MAXSESSION
) return 0;
638 // actually send a control message for a specific tunnel
639 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
641 struct sockaddr_in addr
;
643 CSTAT(call_tunnelsend
);
647 static int backtrace_count
= 0;
648 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
649 STAT(tunnel_tx_errors
);
650 log_backtrace(backtrace_count
, 5)
656 static int backtrace_count
= 0;
657 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
658 log_backtrace(backtrace_count
, 5)
659 STAT(tunnel_tx_errors
);
663 memset(&addr
, 0, sizeof(addr
));
664 addr
.sin_family
= AF_INET
;
665 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
666 addr
.sin_port
= htons(tunnel
[t
].port
);
668 // sequence expected, if sequence in message
669 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
671 // If this is a control message, deal with retries
674 tunnel
[t
].last
= time_now
; // control message sent
675 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
676 if (tunnel
[t
].try > 1)
678 STAT(tunnel_retries
);
679 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
683 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
685 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
686 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
687 STAT(tunnel_tx_errors
);
691 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
692 STAT(tunnel_tx_packets
);
693 INC_STAT(tunnel_tx_bytes
, l
);
697 // Tiny helper function to write data to
700 int tun_write(uint8_t * data
, int size
)
702 return write(tunfd
, data
, size
);
705 // process outgoing (to tunnel) IP
707 static void processipout(uint8_t * buf
, int len
)
714 char * data
= buf
; // Keep a copy of the originals.
717 uint8_t b
[MAXETHER
+ 20];
719 CSTAT(call_processipout
);
721 if (len
< MIN_IP_SIZE
)
723 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
724 STAT(tunnel_tx_errors
);
729 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
730 STAT(tunnel_tx_errors
);
734 // Skip the tun header
738 // Got an IP header now
739 if (*(uint8_t *)(buf
) >> 4 != 4)
741 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
745 ip
= *(uint32_t *)(buf
+ 16);
746 if (!(s
= sessionbyip(ip
)))
748 // Is this a packet for a session that doesn't exist?
749 static int rate
= 0; // Number of ICMP packets we've sent this second.
750 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
752 if (last
!= time_now
)
758 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
760 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
761 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
765 t
= session
[s
].tunnel
;
768 // run access-list if any
769 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
774 // Are we throttling this session?
775 if (config
->cluster_iam_master
)
776 tbf_queue_packet(sp
->tbf_out
, data
, size
);
778 master_throttle_packet(sp
->tbf_out
, data
, size
);
781 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
783 // We are walled-gardening this
784 master_garden_packet(s
, data
, size
);
788 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
790 // Add on L2TP header
792 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
794 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
797 // Snooping this session, send it to intercept box
798 if (sp
->snoop_ip
&& sp
->snoop_port
)
799 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
801 sp
->cout
+= len
; // byte count
802 sp
->total_cout
+= len
; // byte count
805 sess_count
[s
].cout
+= len
; // To send to master..
809 // Helper routine for the TBF filters.
810 // Used to send queued data in to the user!
812 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
818 uint8_t b
[MAXETHER
+ 20];
820 if (len
< 0 || len
> MAXETHER
)
822 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
826 // Skip the tun header
830 ip
= *(in_addr_t
*)(buf
+ 16);
835 t
= session
[s
].tunnel
;
838 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
840 // Add on L2TP header
842 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
844 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
847 // Snooping this session.
848 if (sp
->snoop_ip
&& sp
->snoop_port
)
849 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
851 sp
->cout
+= len
; // byte count
852 sp
->total_cout
+= len
; // byte count
855 sess_count
[s
].cout
+= len
; // To send to master..
858 // add an AVP (16 bit)
859 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
861 uint16_t l
= (m
? 0x8008 : 0x0008);
862 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
863 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
864 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
865 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
869 // add an AVP (32 bit)
870 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
872 uint16_t l
= (m
? 0x800A : 0x000A);
873 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
874 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
875 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
876 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
880 // add an AVP (32 bit)
881 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
883 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
884 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
885 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
886 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
887 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
888 c
->length
+= 6 + strlen(val
);
892 static void controlb(controlt
* c
, uint16_t avp
, char *val
, unsigned int len
, uint8_t m
)
894 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
895 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
896 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
897 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
898 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
899 c
->length
+= 6 + len
;
902 // new control connection
903 static controlt
*controlnew(uint16_t mtype
)
907 c
= malloc(sizeof(controlt
));
911 controlfree
= c
->next
;
915 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
917 control16(c
, 0, mtype
, 1);
921 // send zero block if nothing is waiting
923 static void controlnull(tunnelidt t
)
926 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
929 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
930 *(uint16_t *) (buf
+ 2) = htons(12); // length
931 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
932 *(uint16_t *) (buf
+ 6) = htons(0); // session
933 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
934 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
935 tunnelsend(buf
, 12, t
);
938 // add a control message to a tunnel, and send if within window
939 static void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
941 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
942 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
943 *(uint16_t *) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
944 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
945 tunnel
[t
].ns
++; // advance sequence
946 // link in message in to queue
947 if (tunnel
[t
].controlc
)
948 tunnel
[t
].controle
->next
= c
;
950 tunnel
[t
].controls
= c
;
952 tunnel
[t
].controle
= c
;
953 tunnel
[t
].controlc
++;
955 // send now if space in window
956 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
958 tunnel
[t
].try = 0; // first send
959 tunnelsend(c
->buf
, c
->length
, t
);
964 // Throttle or Unthrottle a session
966 // Throttle the data from/to through a session to no more than
967 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
970 // If either value is -1, the current value is retained for that
973 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
975 if (!session
[s
].tunnel
)
976 return; // No-one home.
978 if (!*session
[s
].user
)
979 return; // User not logged in
983 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
984 if (session
[s
].tbf_in
)
985 free_tbf(session
[s
].tbf_in
);
988 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
990 session
[s
].tbf_in
= 0;
992 session
[s
].throttle_in
= rate_in
;
997 int bytes
= rate_out
* 1024 / 8;
998 if (session
[s
].tbf_out
)
999 free_tbf(session
[s
].tbf_out
);
1002 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1004 session
[s
].tbf_out
= 0;
1006 session
[s
].throttle_out
= rate_out
;
1010 // add/remove filters from session (-1 = no change)
1011 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1013 if (!session
[s
].tunnel
)
1014 return; // No-one home.
1016 if (!*session
[s
].user
)
1017 return; // User not logged in
1020 if (filter_in
> MAXFILTER
) filter_in
= -1;
1021 if (filter_out
> MAXFILTER
) filter_out
= -1;
1022 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1023 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1027 if (session
[s
].filter_in
)
1028 ip_filters
[session
[s
].filter_in
- 1].used
--;
1031 ip_filters
[filter_in
- 1].used
++;
1033 session
[s
].filter_in
= filter_in
;
1036 if (filter_out
>= 0)
1038 if (session
[s
].filter_out
)
1039 ip_filters
[session
[s
].filter_out
- 1].used
--;
1042 ip_filters
[filter_out
- 1].used
++;
1044 session
[s
].filter_out
= filter_out
;
1048 // start tidy shutdown of session
1049 void sessionshutdown(sessionidt s
, char *reason
)
1051 int walled_garden
= session
[s
].walled_garden
;
1054 CSTAT(call_sessionshutdown
);
1056 if (!session
[s
].tunnel
)
1058 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on a session with no tunnel.\n");
1059 return; // not a live session
1062 if (!session
[s
].die
)
1064 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1065 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1066 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1069 if (session
[s
].opened
&& !walled_garden
&& !session
[s
].die
)
1071 // RADIUS Stop message
1072 uint16_t r
= session
[s
].radius
;
1075 if (!(r
= radiusnew(s
)))
1077 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1078 STAT(radius_overflow
);
1083 for (n
= 0; n
< 15; n
++)
1084 radius
[r
].auth
[n
] = rand();
1088 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1089 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1091 // Save counters to dump to accounting file
1092 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1093 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1097 { // IP allocated, clear and unroute
1100 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1102 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1103 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1106 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1107 session
[s
].route
[r
].ip
= 0;
1110 if (session
[s
].ip_pool_index
== -1) // static ip
1112 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1119 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1120 throttle_session(s
, 0, 0);
1123 controlt
*c
= controlnew(14); // sending CDN
1124 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1125 control16(c
, 14, s
, 1); // assigned session (our end)
1126 controladd(c
, session
[s
].tunnel
, s
); // send the message
1129 if (!session
[s
].die
)
1130 session
[s
].die
= now() + 150; // Clean up in 15 seconds
1132 // update filter refcounts
1133 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1134 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1136 cluster_send_session(s
);
1139 void sendipcp(tunnelidt t
, sessionidt s
)
1141 uint8_t buf
[MAXCONTROL
];
1142 uint16_t r
= session
[s
].radius
;
1145 CSTAT(call_sendipcp
);
1150 if (radius
[r
].state
!= RADIUSIPCP
)
1152 radius
[r
].state
= RADIUSIPCP
;
1156 radius
[r
].retry
= backoff(radius
[r
].try++);
1157 if (radius
[r
].try > 10)
1159 radiusclear(r
, s
); // Clear radius session.
1160 sessionshutdown(s
, "No reply on IPCP");
1164 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1168 q
[1] = r
<< RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1169 *(uint16_t *) (q
+ 2) = htons(10);
1172 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1173 config
->bind_address
? config
->bind_address
:
1174 my_address
; // send my IP
1176 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1177 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1180 // kill a session now
1181 static void sessionkill(sessionidt s
, char *reason
)
1184 CSTAT(call_sessionkill
);
1186 session
[s
].die
= now();
1187 sessionshutdown(s
, reason
); // close radius/routes, etc.
1188 if (session
[s
].radius
)
1189 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1191 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1193 memset(&session
[s
], 0, sizeof(session
[s
]));
1194 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1195 session
[s
].next
= sessionfree
;
1197 cli_session_actions
[s
].action
= 0;
1198 cluster_send_session(s
);
1201 static void tunnelclear(tunnelidt t
)
1204 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1205 tunnel
[t
].state
= TUNNELFREE
;
1208 // kill a tunnel now
1209 static void tunnelkill(tunnelidt t
, char *reason
)
1214 CSTAT(call_tunnelkill
);
1216 tunnel
[t
].state
= TUNNELDIE
;
1218 // free control messages
1219 while ((c
= tunnel
[t
].controls
))
1221 controlt
* n
= c
->next
;
1222 tunnel
[t
].controls
= n
;
1223 tunnel
[t
].controlc
--;
1224 c
->next
= controlfree
;
1228 for (s
= 1; s
< MAXSESSION
; s
++)
1229 if (session
[s
].tunnel
== t
)
1230 sessionkill(s
, reason
);
1234 LOG(1, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1235 cli_tunnel_actions
[s
].action
= 0;
1236 cluster_send_tunnel(t
);
1239 // shut down a tunnel cleanly
1240 static void tunnelshutdown(tunnelidt t
, char *reason
)
1244 CSTAT(call_tunnelshutdown
);
1246 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1248 // never set up, can immediately kill
1249 tunnelkill(t
, reason
);
1252 LOG(1, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1255 for (s
= 1; s
< MAXSESSION
; s
++)
1256 if (session
[s
].tunnel
== t
)
1257 sessionshutdown(s
, reason
);
1259 tunnel
[t
].state
= TUNNELDIE
;
1260 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
1261 cluster_send_tunnel(t
);
1262 // TBA - should we wait for sessions to stop?
1264 controlt
*c
= controlnew(4); // sending StopCCN
1265 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message)
1266 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1267 controladd(c
, t
, 0); // send the message
1271 // read and process packet on tunnel (UDP)
1272 void processudp(uint8_t * buf
, int len
, struct sockaddr_in
*addr
)
1274 char *chapresponse
= NULL
;
1275 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1276 uint8_t *p
= buf
+ 2;
1279 CSTAT(call_processudp
);
1283 LOG_HEX(5, "UDP Data", buf
, len
);
1284 STAT(tunnel_rx_packets
);
1285 INC_STAT(tunnel_rx_bytes
, len
);
1288 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
1289 STAT(tunnel_rx_errors
);
1292 if ((buf
[1] & 0x0F) != 2)
1294 LOG(1, 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1295 STAT(tunnel_rx_errors
);
1300 l
= ntohs(*(uint16_t *) p
);
1303 t
= ntohs(*(uint16_t *) p
);
1305 s
= ntohs(*(uint16_t *) p
);
1307 if (s
>= MAXSESSION
)
1309 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
1310 STAT(tunnel_rx_errors
);
1315 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
1316 STAT(tunnel_rx_errors
);
1321 ns
= ntohs(*(uint16_t *) p
);
1323 nr
= ntohs(*(uint16_t *) p
);
1328 uint16_t o
= ntohs(*(uint16_t *) p
);
1333 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
1334 STAT(tunnel_rx_errors
);
1340 uint16_t message
= 0xFFFF; // message type
1342 uint8_t mandatorymessage
= 0;
1343 uint8_t chap
= 0; // if CHAP being used
1344 uint16_t asession
= 0; // assigned session
1345 uint32_t amagic
= 0; // magic number
1346 uint8_t aflags
= 0; // flags from last LCF
1347 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1348 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1349 char called
[MAXTEL
] = ""; // called number
1350 char calling
[MAXTEL
] = ""; // calling number
1352 if (!config
->cluster_iam_master
)
1354 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1358 if ((*buf
& 0xCA) != 0xC8)
1360 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
1361 STAT(tunnel_rx_errors
);
1365 // check for duplicate tunnel open message
1371 // Is this a duplicate of the first packet? (SCCRQ)
1373 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1375 if (tunnel
[i
].state
!= TUNNELOPENING
||
1376 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
1377 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1380 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
1385 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1386 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1388 // if no tunnel specified, assign one
1391 if (!(t
= new_tunnel()))
1393 LOG(1, 0, 0, "No more tunnels\n");
1394 STAT(tunnel_overflow
);
1398 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
1399 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1400 tunnel
[t
].window
= 4; // default window
1401 STAT(tunnel_created
);
1402 LOG(1, 0, t
, " New tunnel from %s:%u ID %d\n",
1403 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
1406 // If the 'ns' just received is not the 'nr' we're
1407 // expecting, just send an ack and drop it.
1409 // if 'ns' is less, then we got a retransmitted packet.
1410 // if 'ns' is greater than missed a packet. Either way
1411 // we should ignore it.
1412 if (ns
!= tunnel
[t
].nr
)
1414 // is this the sequence we were expecting?
1415 STAT(tunnel_rx_errors
);
1416 LOG(1, 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n",
1417 t
, ns
, tunnel
[t
].nr
);
1419 if (l
) // Is this not a ZLB?
1424 // This is used to time out old tunnels
1425 tunnel
[t
].lastrec
= time_now
;
1427 // check sequence of this message
1429 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1430 // some to clear maybe?
1431 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1433 controlt
*c
= tunnel
[t
].controls
;
1434 tunnel
[t
].controls
= c
->next
;
1435 tunnel
[t
].controlc
--;
1436 c
->next
= controlfree
;
1439 tunnel
[t
].try = 0; // we have progress
1442 // receiver advance (do here so quoted correctly in any sends below)
1443 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1444 if (skip
< 0) skip
= 0;
1445 if (skip
< tunnel
[t
].controlc
)
1447 // some control packets can now be sent that were previous stuck out of window
1448 int tosend
= tunnel
[t
].window
- skip
;
1449 controlt
*c
= tunnel
[t
].controls
;
1457 tunnel
[t
].try = 0; // first send
1458 tunnelsend(c
->buf
, c
->length
, t
);
1463 if (!tunnel
[t
].controlc
)
1464 tunnel
[t
].retry
= 0; // caught up
1467 { // if not a null message
1469 while (l
&& !(fatal
& 0x80))
1471 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
1478 LOG(1, s
, t
, "Invalid length in AVP\n");
1479 STAT(tunnel_rx_errors
);
1486 // handle hidden AVPs
1487 if (!*config
->l2tpsecret
)
1489 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1493 if (!session
[s
].random_vector_length
)
1495 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
1499 LOG(4, s
, t
, "Hidden AVP\n");
1501 n
= unhide_avp(b
, t
, s
, n
);
1510 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1515 if (*(uint16_t *) (b
))
1517 LOG(2, s
, t
, "Unknown AVP vendor %d\n", ntohs(*(uint16_t *) (b
)));
1522 mtype
= ntohs(*(uint16_t *) (b
));
1526 LOG(4, s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1529 case 0: // message type
1530 message
= ntohs(*(uint16_t *) b
);
1531 LOG(4, s
, t
, " Message type = %d (%s)\n", *b
, l2tp_message_types
[message
]);
1532 mandatorymessage
= flags
;
1534 case 1: // result code
1536 uint16_t rescode
= ntohs(*(uint16_t *) b
);
1537 const char* resdesc
= "(unknown)";
1540 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1541 resdesc
= stopccn_result_codes
[rescode
];
1543 else if (message
== 14)
1545 if (rescode
<= MAX_CDN_RESULT_CODE
)
1546 resdesc
= cdn_result_codes
[rescode
];
1549 LOG(4, s
, t
, " Result Code %d: %s\n", rescode
, resdesc
);
1552 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
1553 const char* errdesc
= "(unknown)";
1554 if (errcode
<= MAX_ERROR_CODE
)
1555 errdesc
= error_codes
[errcode
];
1556 LOG(4, s
, t
, " Error Code %d: %s\n", errcode
, errdesc
);
1559 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
1564 case 2: // protocol version
1566 version
= ntohs(*(uint16_t *) (b
));
1567 LOG(4, s
, t
, " Protocol version = %d\n", version
);
1568 if (version
&& version
!= 0x0100)
1569 { // allow 0.0 and 1.0
1570 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
1576 case 3: // framing capabilities
1577 // LOG(4, s, t, "Framing capabilities\n");
1579 case 4: // bearer capabilities
1580 // LOG(4, s, t, "Bearer capabilities\n");
1582 case 5: // tie breaker
1583 // We never open tunnels, so we don't care about tie breakers
1584 // LOG(4, s, t, "Tie breaker\n");
1586 case 6: // firmware revision
1587 // LOG(4, s, t, "Firmware revision\n");
1589 case 7: // host name
1590 memset(tunnel
[t
].hostname
, 0, 128);
1591 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1592 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1593 // TBA - to send to RADIUS
1595 case 8: // vendor name
1596 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1597 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1598 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1600 case 9: // assigned tunnel
1601 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
1602 LOG(4, s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1604 case 10: // rx window
1605 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
1606 if (!tunnel
[t
].window
)
1607 tunnel
[t
].window
= 1; // window of 0 is silly
1608 LOG(4, s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1610 case 11: // Challenge
1612 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
1613 build_chap_response(b
, 2, n
, &chapresponse
);
1616 case 13: // Response
1617 // Why did they send a response? We never challenge.
1618 LOG(2, s
, t
, " received unexpected challenge response\n");
1621 case 14: // assigned session
1622 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
1623 LOG(4, s
, t
, " assigned session = %d\n", asession
);
1625 case 15: // call serial number
1626 LOG(4, s
, t
, " call serial number = %d\n", ntohl(*(uint32_t *)b
));
1628 case 18: // bearer type
1629 LOG(4, s
, t
, " bearer type = %d\n", ntohl(*(uint32_t *)b
));
1632 case 19: // framing type
1633 LOG(4, s
, t
, " framing type = %d\n", ntohl(*(uint32_t *)b
));
1636 case 21: // called number
1637 memset(called
, 0, MAXTEL
);
1638 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1639 LOG(4, s
, t
, " Called <%s>\n", called
);
1641 case 22: // calling number
1642 memset(calling
, 0, MAXTEL
);
1643 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1644 LOG(4, s
, t
, " Calling <%s>\n", calling
);
1648 case 24: // tx connect speed
1651 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
1655 // AS5300s send connect speed as a string
1657 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1658 session
[s
].tx_connect_speed
= atol(tmp
);
1660 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
1662 case 38: // rx connect speed
1665 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
1669 // AS5300s send connect speed as a string
1671 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1672 session
[s
].rx_connect_speed
= atol(tmp
);
1674 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
1676 case 25: // Physical Channel ID
1678 uint32_t tmp
= ntohl(*(uint32_t *) b
);
1679 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
1682 case 29: // Proxy Authentication Type
1684 uint16_t authtype
= ntohs(*(uint16_t *)b
);
1685 LOG(4, s
, t
, " Proxy Auth Type %d (%s)\n", authtype
, authtypes
[authtype
]);
1686 requestchap
= (authtype
== 2);
1689 case 30: // Proxy Authentication Name
1691 char authname
[64] = {0};
1692 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1693 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
1697 case 31: // Proxy Authentication Challenge
1699 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1700 LOG(4, s
, t
, " Proxy Auth Challenge\n");
1703 case 32: // Proxy Authentication ID
1705 uint16_t authid
= ntohs(*(uint16_t *)(b
));
1706 LOG(4, s
, t
, " Proxy Auth ID (%d)\n", authid
);
1707 if (session
[s
].radius
)
1708 radius
[session
[s
].radius
].id
= authid
;
1711 case 33: // Proxy Authentication Response
1713 char authresp
[64] = {0};
1714 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1715 LOG(4, s
, t
, " Proxy Auth Response\n");
1718 case 27: // last send lcp
1719 { // find magic number
1720 uint8_t *p
= b
, *e
= p
+ n
;
1721 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1723 if (*p
== 5 && p
[1] == 6) // Magic-Number
1724 amagic
= ntohl(*(uint32_t *) (p
+ 2));
1725 else if (*p
== 3 && p
[1] == 5 && *(uint16_t *) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1727 else if (*p
== 7) // Protocol-Field-Compression
1728 aflags
|= SESSIONPFC
;
1729 else if (*p
== 8) // Address-and-Control-Field-Compression
1730 aflags
|= SESSIONACFC
;
1735 case 28: // last recv lcp confreq
1737 case 26: // Initial Received LCP CONFREQ
1739 case 39: // seq required - we control it as an LNS anyway...
1741 case 36: // Random Vector
1742 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1743 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1744 memcpy(session
[s
].random_vector
, b
, n
);
1745 session
[s
].random_vector_length
= n
;
1748 LOG(2, s
, t
, " Unknown AVP type %d\n", mtype
);
1755 tunnelshutdown(t
, "Unknown Mandatory AVP");
1759 case 1: // SCCRQ - Start Control Connection Request
1761 controlt
*c
= controlnew(2); // sending SCCRP
1762 control16(c
, 2, version
, 1); // protocol version
1763 control32(c
, 3, 3, 1); // framing
1764 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1765 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1766 control16(c
, 9, t
, 1); // assigned tunnel
1767 controladd(c
, t
, s
); // send the resply
1769 tunnel
[t
].state
= TUNNELOPENING
;
1772 tunnel
[t
].state
= TUNNELOPEN
;
1775 tunnel
[t
].state
= TUNNELOPEN
;
1776 controlnull(t
); // ack
1779 controlnull(t
); // ack
1780 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1781 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1784 controlnull(t
); // simply ACK
1798 STAT(session_overflow
);
1799 tunnelshutdown(t
, "No free sessions");
1807 sessionfree
= session
[s
].next
;
1808 memset(&session
[s
], 0, sizeof(session
[s
]));
1810 if (s
> config
->cluster_highest_sessionid
)
1811 config
->cluster_highest_sessionid
= s
;
1813 // make a RADIUS session
1814 if (!(r
= radiusnew(s
)))
1816 LOG(1, s
, t
, "No free RADIUS sessions for ICRQ\n");
1817 sessionkill(s
, "no free RADIUS sesions");
1821 c
= controlnew(11); // sending ICRP
1822 session
[s
].id
= sessionid
++;
1823 session
[s
].opened
= time(NULL
);
1824 session
[s
].tunnel
= t
;
1825 session
[s
].far
= asession
;
1826 session
[s
].last_packet
= time_now
;
1827 LOG(3, s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1828 control16(c
, 14, s
, 1); // assigned session
1829 controladd(c
, t
, s
); // send the reply
1831 // Generate a random challenge
1833 for (n
= 0; n
< 15; n
++)
1834 radius
[r
].auth
[n
] = rand();
1836 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1837 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1838 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1839 STAT(session_created
);
1846 if (amagic
== 0) amagic
= time_now
;
1847 session
[s
].magic
= amagic
; // set magic number
1848 session
[s
].l2tp_flags
= aflags
; // set flags received
1849 LOG(3, s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1850 controlnull(t
); // ack
1851 // In CHAP state, request PAP instead
1856 controlnull(t
); // ack
1857 sessionshutdown(s
, "Closed (Received CDN)");
1860 LOG(1, s
, t
, "Missing message type\n");
1863 STAT(tunnel_rx_errors
);
1864 if (mandatorymessage
& 0x80)
1865 tunnelshutdown(t
, "Unknown message");
1867 LOG(1, s
, t
, "Unknown message type %d\n", message
);
1870 if (chapresponse
) free(chapresponse
);
1871 cluster_send_tunnel(t
);
1875 LOG(4, s
, t
, " Got a ZLB ack\n");
1882 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
1883 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1884 { // HDLC address header, discard
1890 LOG(1, s
, t
, "Short ppp length %d\n", l
);
1891 STAT(tunnel_rx_errors
);
1901 prot
= ntohs(*(uint16_t *) p
);
1906 if (s
&& !session
[s
].tunnel
) // Is something wrong??
1908 if (!config
->cluster_iam_master
)
1910 // Pass it off to the master to deal with..
1911 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1916 LOG(1, s
, t
, "UDP packet contains session %d but no session[%d].tunnel "
1917 "exists (LAC said tunnel = %d). Dropping packet.\n", s
, s
, t
);
1919 STAT(tunnel_rx_errors
);
1925 session
[s
].last_packet
= time_now
;
1926 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1927 processpap(t
, s
, p
, l
);
1929 else if (prot
== PPPCHAP
)
1931 session
[s
].last_packet
= time_now
;
1932 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1933 processchap(t
, s
, p
, l
);
1935 else if (prot
== PPPLCP
)
1937 session
[s
].last_packet
= time_now
;
1938 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1939 processlcp(t
, s
, p
, l
);
1941 else if (prot
== PPPIPCP
)
1943 session
[s
].last_packet
= time_now
;
1944 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1945 processipcp(t
, s
, p
, l
);
1947 else if (prot
== PPPCCP
)
1949 session
[s
].last_packet
= time_now
;
1950 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1951 processccp(t
, s
, p
, l
);
1953 else if (prot
== PPPIP
)
1957 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1958 return; // closing session, PPP not processed
1961 session
[s
].last_packet
= time_now
;
1962 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
1964 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1968 processipin(t
, s
, p
, l
);
1972 STAT(tunnel_rx_errors
);
1973 LOG(1, s
, t
, "Unknown PPP protocol %04X\n", prot
);
1978 // read and process packet on tun
1979 static void processtun(uint8_t * buf
, int len
)
1981 LOG_HEX(5, "Receive TUN Data", buf
, len
);
1982 STAT(tun_rx_packets
);
1983 INC_STAT(tun_rx_bytes
, len
);
1985 CSTAT(call_processtun
);
1991 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
1992 STAT(tun_rx_errors
);
1996 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
1997 processipout(buf
, len
);
2002 // Maximum number of actions to complete.
2003 // This is to avoid sending out too many packets
2005 #define MAX_ACTIONS 500
2007 static int regular_cleanups(void)
2009 static sessionidt s
= 0; // Next session to check for actions on.
2013 static clockt next_acct
= 0;
2014 static clockt next_shut_acct
= 0;
2017 LOG(3, 0, 0, "Begin regular cleanup\n");
2019 for (r
= 1; r
< MAXRADIUS
; r
++)
2021 if (!radius
[r
].state
)
2023 if (radius
[r
].retry
)
2025 if (radius
[r
].retry
<= TIME
)
2028 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
2030 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
2032 // check for expired tunnels
2033 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2035 STAT(tunnel_timeout
);
2036 tunnelkill(t
, "Expired");
2039 // check for message resend
2040 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2042 // resend pending messages as timeout on reply
2043 if (tunnel
[t
].retry
<= TIME
)
2045 controlt
*c
= tunnel
[t
].controls
;
2046 uint8_t w
= tunnel
[t
].window
;
2047 tunnel
[t
].try++; // another try
2048 if (tunnel
[t
].try > 5)
2049 tunnelkill(t
, "Timeout on control message"); // game over
2053 tunnelsend(c
->buf
, c
->length
, t
);
2059 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2061 controlt
*c
= controlnew(6); // sending HELLO
2062 controladd(c
, t
, 0); // send the message
2063 LOG(3, 0, t
, "Sending HELLO message\n");
2066 // Check for tunnel changes requested from the CLI
2067 if ((a
= cli_tunnel_actions
[t
].action
))
2069 cli_tunnel_actions
[t
].action
= 0;
2070 if (a
& CLI_TUN_KILL
)
2072 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
2073 tunnelshutdown(t
, "Requested by administrator");
2080 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2083 if (s
> config
->cluster_highest_sessionid
)
2086 if (!session
[s
].tunnel
) // Session isn't in use
2089 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2091 // IPCP has not completed yet. Resend
2092 LOG(3, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2093 sendipcp(session
[s
].tunnel
, s
);
2096 // check for expired sessions
2097 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2099 sessionkill(s
, "Expired");
2100 if (++count
>= MAX_ACTIONS
) break;
2104 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2105 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2107 sessionshutdown(s
, "No response to LCP ECHO requests");
2108 STAT(session_timeout
);
2109 if (++count
>= MAX_ACTIONS
) break;
2113 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2114 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2116 uint8_t b
[MAXCONTROL
] = {0};
2118 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2122 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
2123 *(uint16_t *)(q
+ 2) = htons(8); // Length
2124 *(uint32_t *)(q
+ 4) = 0; // Magic Number (not supported)
2126 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2127 (int)(time_now
- session
[s
].last_packet
));
2128 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2129 if (++count
>= MAX_ACTIONS
) break;
2132 // Check for actions requested from the CLI
2133 if ((a
= cli_session_actions
[s
].action
))
2137 cli_session_actions
[s
].action
= 0;
2138 if (a
& CLI_SESS_KILL
)
2140 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2141 sessionshutdown(s
, "Requested by administrator");
2142 a
= 0; // dead, no need to check for other actions
2145 if (a
& CLI_SESS_NOSNOOP
)
2147 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2148 session
[s
].snoop_ip
= 0;
2149 session
[s
].snoop_port
= 0;
2152 else if (a
& CLI_SESS_SNOOP
)
2154 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2155 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
2156 cli_session_actions
[s
].snoop_port
);
2158 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2159 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2163 if (a
& CLI_SESS_NOTHROTTLE
)
2165 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2166 throttle_session(s
, 0, 0);
2169 else if (a
& CLI_SESS_THROTTLE
)
2171 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2172 cli_session_actions
[s
].throttle_in
,
2173 cli_session_actions
[s
].throttle_out
);
2175 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2179 if (a
& CLI_SESS_NOFILTER
)
2181 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
2182 filter_session(s
, 0, 0);
2185 else if (a
& CLI_SESS_FILTER
)
2187 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
2188 cli_session_actions
[s
].filter_in
,
2189 cli_session_actions
[s
].filter_out
);
2191 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
2196 cluster_send_session(s
);
2198 if (++count
>= MAX_ACTIONS
) break;
2202 if (*config
->accounting_dir
)
2204 if (next_acct
<= TIME
)
2206 // Dump accounting data
2207 next_acct
= TIME
+ ACCT_TIME
;
2208 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2211 else if (next_shut_acct
<= TIME
)
2213 // Dump accounting data for shutdown sessions
2214 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2220 if (count
>= MAX_ACTIONS
)
2221 return 1; // Didn't finish!
2223 LOG(3, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count
, config
->cleanup_interval
);
2229 // Are we in the middle of a tunnel update, or radius
2232 static int still_busy(void)
2235 static clockt last_talked
= 0;
2236 static clockt start_busy_wait
= 0;
2237 if (start_busy_wait
== 0)
2238 start_busy_wait
= TIME
;
2240 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2242 if (!tunnel
[i
].controlc
)
2245 if (last_talked
!= TIME
)
2247 LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i
);
2253 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2254 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2256 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2260 for (i
= 1; i
< MAXRADIUS
; i
++)
2262 if (radius
[i
].state
== RADIUSNULL
)
2264 if (radius
[i
].state
== RADIUSWAIT
)
2267 if (last_talked
!= TIME
)
2269 LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2278 static fd_set readset
;
2279 static int readset_n
= 0;
2281 // main loop - gets packets on tun or udp and processes them
2282 static void mainloop(void)
2287 clockt next_cluster_ping
= 0; // send initial ping immediately
2288 time_t next_clean
= time_now
+ config
->cleanup_interval
;
2290 LOG(4, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2291 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2294 FD_SET(udpfd
, &readset
);
2295 FD_SET(tunfd
, &readset
);
2296 FD_SET(controlfd
, &readset
);
2297 FD_SET(clifd
, &readset
);
2298 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2300 if (tunfd
> readset_n
) readset_n
= tunfd
;
2301 if (controlfd
> readset_n
) readset_n
= controlfd
;
2302 if (clifd
> readset_n
) readset_n
= clifd
;
2303 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2305 while (!main_quit
|| still_busy())
2311 int bgp_set
[BGP_NUM_PEERS
];
2314 if (config
->reload_config
)
2316 // Update the config state based on config settings
2320 memcpy(&r
, &readset
, sizeof(fd_set
));
2322 to
.tv_usec
= 100000; // 1/10th of a second.
2326 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2328 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2331 FD_SET(bgp_peers
[i
].sock
, &r
);
2332 if (bgp_peers
[i
].sock
> n
)
2333 n
= bgp_peers
[i
].sock
;
2338 FD_SET(bgp_peers
[i
].sock
, &w
);
2339 if (bgp_peers
[i
].sock
> n
)
2340 n
= bgp_peers
[i
].sock
;
2344 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2346 n
= select(n
+ 1, &r
, 0, 0, &to
);
2349 STAT(select_called
);
2354 if (errno
== EINTR
||
2355 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2358 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2364 struct sockaddr_in addr
;
2368 int cluster_pkts
= 0;
2371 if (FD_ISSET(controlfd
, &r
))
2373 alen
= sizeof(addr
);
2374 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
, alen
);
2379 if (config
->cluster_iam_master
)
2381 for (i
= 0; i
< config
->num_radfds
; i
++)
2383 if (FD_ISSET(radfds
[i
], &r
))
2385 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2392 if (FD_ISSET(clifd
, &r
))
2396 alen
= sizeof(addr
);
2397 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
2403 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
2409 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2411 int isr
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0;
2412 int isw
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0;
2413 bgp_process(&bgp_peers
[i
], isr
, isw
);
2419 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
2422 if (FD_ISSET(udpfd
, &r
))
2424 alen
= sizeof(addr
);
2425 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
2427 processudp(buf
, s
, &addr
);
2438 if (FD_ISSET(tunfd
, &r
))
2440 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
2453 if (FD_ISSET(cluster_sockfd
, &r
))
2455 alen
= sizeof(addr
);
2456 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
2458 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
2463 FD_CLR(cluster_sockfd
, &r
);
2469 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
2470 STAT(multi_read_used
);
2472 if (c
>= config
->multi_read_count
)
2474 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
2475 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
2477 STAT(multi_read_exceeded
);
2481 // Runs on every machine (master and slaves).
2482 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
2484 // Check to see which of the cluster is still alive..
2486 cluster_send_ping(basetime
); // Only does anything if we're a slave
2487 cluster_check_master(); // ditto.
2489 cluster_heartbeat(); // Only does anything if we're a master.
2490 cluster_check_slaves(); // ditto.
2492 master_update_counts(); // If we're a slave, send our byte counters to our master.
2494 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
2495 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
2497 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
2500 // Run token bucket filtering queue..
2501 // Only run it every 1/10th of a second.
2502 // Runs on all machines both master and slave.
2504 static clockt last_run
= 0;
2505 if (last_run
!= TIME
)
2512 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2513 * something to read, else under load this will never actually run....
2516 if (config
->cluster_iam_master
&& next_clean
<= time_now
)
2518 if (regular_cleanups())
2521 next_clean
= time_now
+ 1 ; // Didn't finish. Check quickly.
2525 next_clean
= time_now
+ config
->cleanup_interval
; // Did. Move to next interval.
2530 // Are we the master and shutting down??
2531 if (config
->cluster_iam_master
)
2532 cluster_heartbeat(); // Flush any queued changes..
2534 // Ok. Notify everyone we're shutting down. If we're
2535 // the master, this will force an election.
2536 cluster_send_ping(0);
2539 // Important!!! We MUST not process any packets past this point!
2542 static void stripdomain(char *host
)
2546 if ((p
= strchr(host
, '.')))
2552 FILE *resolv
= fopen("/etc/resolv.conf", "r");
2558 while (fgets(buf
, sizeof(buf
), resolv
))
2560 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
2563 if (!isspace(buf
[6]))
2567 while (isspace(*b
)) b
++;
2572 while (*b
&& !isspace(*b
)) b
++;
2574 if (buf
[0] == 'd') // domain is canonical
2580 // first search line
2583 // hold, may be subsequent domain line
2584 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
2595 int hl
= strlen(host
);
2596 int dl
= strlen(domain
);
2597 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
2598 host
[hl
-dl
- 1] = 0;
2602 *p
= 0; // everything after first dot
2607 // Init data structures
2608 static void initdata(int optdebug
, char *optconfig
)
2612 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
2614 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
2617 if (!(config
= shared_malloc(sizeof(configt
))))
2619 LOG(0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2622 memset(config
, 0, sizeof(configt
));
2623 time(&config
->start_time
);
2624 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
2625 config
->debug
= optdebug
;
2626 config
->num_tbfs
= MAXTBFS
;
2627 config
->rl_rate
= 28; // 28kbps
2629 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
2631 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
2634 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
2636 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
2640 if (!(sess_count
= shared_malloc(sizeof(sessioncountt
) * MAXSESSION
)))
2642 LOG(0, 0, 0, "Error doing malloc for sessions_count: %s\n", strerror(errno
));
2646 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
2648 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
2652 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
2654 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
2658 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
2660 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
2663 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
2666 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2668 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2671 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2674 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2676 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2679 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2681 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2683 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2686 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2688 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2689 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2690 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2691 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2693 // Put all the sessions on the free list marked as undefined.
2694 for (i
= 1; i
< MAXSESSION
- 1; i
++)
2696 session
[i
].next
= i
+ 1;
2697 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2699 session
[MAXSESSION
- 1].next
= 0;
2702 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2703 for (i
= 1; i
< MAXTUNNEL
- 1; i
++)
2704 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2708 // Grab my hostname unless it's been specified
2709 gethostname(hostname
, sizeof(hostname
));
2710 stripdomain(hostname
);
2713 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2716 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2718 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2724 static int assign_ip_address(sessionidt s
)
2728 time_t best_time
= time_now
;
2729 char *u
= session
[s
].user
;
2733 CSTAT(call_assign_ip_address
);
2735 for (i
= 1; i
< ip_pool_size
; i
++)
2737 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2740 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2747 if (ip_address_pool
[i
].last
< best_time
)
2750 if (!(best_time
= ip_address_pool
[i
].last
))
2751 break; // never used, grab this one
2757 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2761 session
[s
].ip
= ip_address_pool
[best
].address
;
2762 session
[s
].ip_pool_index
= best
;
2763 ip_address_pool
[best
].assigned
= 1;
2764 ip_address_pool
[best
].last
= time_now
;
2765 ip_address_pool
[best
].session
= s
;
2766 if (session
[s
].walled_garden
)
2767 /* Don't track addresses of users in walled garden (note: this
2768 means that their address isn't "sticky" even if they get
2770 ip_address_pool
[best
].user
[0] = 0;
2772 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2775 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
2776 reuse
? "Reusing" : "Allocating", best
);
2781 static void free_ip_address(sessionidt s
)
2783 int i
= session
[s
].ip_pool_index
;
2786 CSTAT(call_free_ip_address
);
2789 return; // what the?
2791 if (i
< 0) // Is this actually part of the ip pool?
2795 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2797 ip_address_pool
[i
].assigned
= 0;
2798 ip_address_pool
[i
].session
= 0;
2799 ip_address_pool
[i
].last
= time_now
;
2803 // Fsck the address pool against the session table.
2804 // Normally only called when we become a master.
2806 // This isn't perfect: We aren't keep tracking of which
2807 // users used to have an IP address.
2809 void rebuild_address_pool(void)
2814 // Zero the IP pool allocation, and build
2815 // a map from IP address to pool index.
2816 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2818 ip_address_pool
[i
].assigned
= 0;
2819 ip_address_pool
[i
].session
= 0;
2820 if (!ip_address_pool
[i
].address
)
2823 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2826 for (i
= 0; i
< MAXSESSION
; ++i
)
2829 if (!session
[i
].ip
|| !session
[i
].tunnel
)
2831 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2833 if (session
[i
].ip_pool_index
< 0)
2835 // Not allocated out of the pool.
2836 if (ipid
< 1) // Not found in the pool either? good.
2839 LOG(0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2840 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
2842 // Fall through and process it as part of the pool.
2846 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2848 LOG(0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2850 session
[i
].ip_pool_index
= ipid
;
2854 ip_address_pool
[ipid
].assigned
= 1;
2855 ip_address_pool
[ipid
].session
= i
;
2856 ip_address_pool
[ipid
].last
= time_now
;
2857 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2858 session
[i
].ip_pool_index
= ipid
;
2859 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
2864 // Fix the address pool to match a changed session.
2865 // (usually when the master sends us an update).
2866 static void fix_address_pool(int sid
)
2870 ipid
= session
[sid
].ip_pool_index
;
2872 if (ipid
> ip_pool_size
)
2873 return; // Ignore it. rebuild_address_pool will fix it up.
2875 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
2876 return; // Just ignore it. rebuild_address_pool will take care of it.
2878 ip_address_pool
[ipid
].assigned
= 1;
2879 ip_address_pool
[ipid
].session
= sid
;
2880 ip_address_pool
[ipid
].last
= time_now
;
2881 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2885 // Add a block of addresses to the IP pool to hand out.
2887 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
2891 mask
= 0xffffffff; // Host route only.
2895 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
2898 for (i
= addr
;(i
& mask
) == addr
; ++i
)
2900 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
2901 continue; // Skip 0 and broadcast addresses.
2903 ip_address_pool
[ip_pool_size
].address
= i
;
2904 ip_address_pool
[ip_pool_size
].assigned
= 0;
2906 if (ip_pool_size
>= MAXIPPOOL
)
2908 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
2914 // Initialize the IP address pool
2915 static void initippool()
2920 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2922 if (!(f
= fopen(IPPOOLFILE
, "r")))
2924 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2928 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2931 buf
[4095] = 0; // Force it to be zero terminated/
2933 if (*buf
== '#' || *buf
== '\n')
2934 continue; // Skip comments / blank lines
2935 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2936 if ((p
= (char *)strchr(buf
, ':')))
2940 src
= inet_addr(buf
);
2941 if (src
== INADDR_NONE
)
2943 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
2946 // This entry is for a specific IP only
2947 if (src
!= config
->bind_address
)
2952 if ((p
= (char *)strchr(pool
, '/')))
2956 in_addr_t start
= 0, mask
= 0;
2958 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
2960 if (!*p
|| !(numbits
= atoi(p
)))
2962 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
2965 start
= ntohl(inet_addr(pool
));
2966 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
2968 // Add a static route for this pool
2969 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
2970 fmtaddr(htonl(start
), 0), 32 + mask
);
2972 routeset(0, start
, mask
, 0, 1);
2974 add_to_ip_pool(start
, mask
);
2978 // It's a single ip address
2979 add_to_ip_pool(inet_addr(pool
), 0);
2983 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
2986 void snoop_send_packet(char *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
2988 struct sockaddr_in snoop_addr
= {0};
2989 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2992 snoop_addr
.sin_family
= AF_INET
;
2993 snoop_addr
.sin_addr
.s_addr
= destination
;
2994 snoop_addr
.sin_port
= ntohs(port
);
2996 LOG(5, 0, 0, "Snooping %d byte packet to %s:%d\n", size
,
2997 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
2998 htons(snoop_addr
.sin_port
));
3000 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
3001 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
3003 STAT(packets_snooped
);
3006 static int dump_session(FILE **f
, sessiont
*s
)
3008 if (!s
->opened
|| !s
->ip
|| !(s
->cin
|| s
->cout
) || !*s
->user
|| s
->walled_garden
)
3013 char filename
[1024];
3015 time_t now
= time(NULL
);
3017 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
3018 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
3020 if (!(*f
= fopen(filename
, "w")))
3022 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
3026 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
3027 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
3031 "# format: username ip qos uptxoctets downrxoctets\n",
3037 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
3038 fprintf(*f
, "%s %s %d %u %u\n",
3039 s
->user
, // username
3040 fmtaddr(htonl(s
->ip
), 0), // ip
3041 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
3042 (uint32_t) s
->cin
, // uptxoctets
3043 (uint32_t) s
->cout
); // downrxoctets
3045 s
->pin
= s
->cin
= 0;
3046 s
->pout
= s
->cout
= 0;
3051 static void dump_acct_info(int all
)
3057 CSTAT(call_dump_acct_info
);
3061 for (i
= 0; i
< shut_acct_n
; i
++)
3062 dump_session(&f
, &shut_acct
[i
]);
3068 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3069 dump_session(&f
, &session
[i
]);
3076 int main(int argc
, char *argv
[])
3080 char *optconfig
= CONFIGFILE
;
3082 time(&basetime
); // start clock
3085 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
3090 if (fork()) exit(0);
3092 freopen("/dev/null", "r", stdin
);
3093 freopen("/dev/null", "w", stdout
);
3094 freopen("/dev/null", "w", stderr
);
3103 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
3106 printf("Args are:\n"
3107 "\t-d\t\tDetach from terminal\n"
3108 "\t-c <file>\tConfig file\n"
3109 "\t-h <hostname>\tForce hostname\n"
3117 // Start the timer routine off
3119 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3120 signal(SIGALRM
, sigalrm_handler
);
3121 siginterrupt(SIGALRM
, 0);
3124 initdata(optdebug
, optconfig
);
3128 init_tbf(config
->num_tbfs
);
3130 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
3131 LOG(0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
3132 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3135 rlim
.rlim_cur
= RLIM_INFINITY
;
3136 rlim
.rlim_max
= RLIM_INFINITY
;
3137 // Remove the maximum core size
3138 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
3139 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
3141 // Make core dumps go to /tmp
3145 if (config
->scheduler_fifo
)
3148 struct sched_param params
= {0};
3149 params
.sched_priority
= 1;
3151 if (get_nprocs() < 2)
3153 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3154 config
->scheduler_fifo
= 0;
3158 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3160 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3164 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3165 config
->scheduler_fifo
= 0;
3170 /* Set up the cluster communications port. */
3171 if (cluster_init() < 0)
3175 signal(SIGPIPE
, SIG_IGN
);
3176 bgp_setup(config
->as_number
);
3177 bgp_add_route(config
->bind_address
, 0xffffffff);
3178 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3180 if (config
->neighbour
[i
].name
[0])
3181 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3182 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3183 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3188 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3196 signal(SIGHUP
, sighup_handler
);
3197 signal(SIGTERM
, sigterm_handler
);
3198 signal(SIGINT
, sigterm_handler
);
3199 signal(SIGQUIT
, sigquit_handler
);
3200 signal(SIGCHLD
, sigchild_handler
);
3202 // Prevent us from getting paged out
3203 if (config
->lock_pages
)
3205 if (!mlockall(MCL_CURRENT
))
3206 LOG(1, 0, 0, "Locking pages into memory\n");
3208 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3213 // Drop privileges here
3214 if (config
->target_uid
> 0 && geteuid() == 0)
3215 setuid(config
->target_uid
);
3220 /* try to shut BGP down cleanly; with luck the sockets will be
3221 writable since we're out of the select */
3222 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3223 if (bgp_peers
[i
].state
== Established
)
3224 bgp_stop(&bgp_peers
[i
]);
3227 /* remove plugins (so cleanup code gets run) */
3230 // Remove the PID file if we wrote it
3231 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3232 unlink(config
->pid_file
);
3234 /* kill CLI children */
3235 signal(SIGTERM
, SIG_IGN
);
3240 static void sighup_handler(int sig
)
3242 if (log_stream
&& log_stream
!= stderr
)
3251 static void sigalrm_handler(int sig
)
3253 // Log current traffic stats
3255 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3256 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3257 (udp_rx
/ 1024.0 / 1024.0 * 8),
3258 (eth_tx
/ 1024.0 / 1024.0 * 8),
3259 (eth_rx
/ 1024.0 / 1024.0 * 8),
3260 (udp_tx
/ 1024.0 / 1024.0 * 8),
3261 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3262 udp_rx_pkt
, eth_rx_pkt
);
3264 udp_tx
= udp_rx
= 0;
3265 udp_rx_pkt
= eth_rx_pkt
= 0;
3266 eth_tx
= eth_rx
= 0;
3268 if (config
->dump_speed
)
3269 printf("%s\n", config
->bandwidth
);
3271 // Update the internal time counter
3273 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3278 struct param_timer p
= { time_now
};
3279 run_plugins(PLUGIN_TIMER
, &p
);
3284 static void sigterm_handler(int sig
)
3286 LOG(1, 0, 0, "Shutting down cleanly\n");
3287 if (config
->save_state
)
3293 static void sigquit_handler(int sig
)
3297 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3299 if (config
->cluster_iam_master
)
3301 for (i
= 1; i
< MAXSESSION
; i
++)
3303 if (session
[i
].opened
)
3304 sessionkill(i
, "L2TPNS Closing");
3306 for (i
= 1; i
< MAXTUNNEL
; i
++)
3308 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3309 tunnelshutdown(i
, "L2TPNS Closing");
3316 static void sigchild_handler(int sig
)
3318 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3322 static void read_state()
3328 char magic
[sizeof(DUMP_MAGIC
) - 1];
3331 if (!config
->save_state
)
3337 if (stat(STATEFILE
, &sb
) < 0)
3343 if (sb
.st_mtime
< (time(NULL
) - 60))
3345 LOG(0, 0, 0, "State file is too old to read, ignoring\n");
3350 f
= fopen(STATEFILE
, "r");
3355 LOG(0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3359 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3361 LOG(0, 0, 0, "Bad state file magic\n");
3365 LOG(1, 0, 0, "Reading state information\n");
3366 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3368 LOG(0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3372 if (buf
[0] > ip_pool_size
)
3374 LOG(0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3378 LOG(2, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3379 for (i
= 0; i
< buf
[0]; i
++)
3381 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3383 LOG(0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3387 if (itmp
.address
!= ip_address_pool
[i
].address
)
3389 LOG(0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3393 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3396 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3398 LOG(0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3402 LOG(2, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3403 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3405 LOG(0, 0, 0, "Error reading tunnel data from state file\n");
3409 for (i
= 0; i
< MAXTUNNEL
; i
++)
3411 tunnel
[i
].controlc
= 0;
3412 tunnel
[i
].controls
= NULL
;
3413 tunnel
[i
].controle
= NULL
;
3414 if (*tunnel
[i
].hostname
)
3415 LOG(3, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3418 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3420 LOG(0, 0, 0, "Error/mismatch reading session header from state file\n");
3424 LOG(2, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3425 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3427 LOG(0, 0, 0, "Error reading session data from state file\n");
3431 for (i
= 0; i
< MAXSESSION
; i
++)
3433 session
[i
].tbf_in
= 0;
3434 session
[i
].tbf_out
= 0;
3435 if (session
[i
].opened
)
3437 LOG(2, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3439 sessionsetup(session
[i
].tunnel
, i
);
3444 LOG(0, 0, 0, "Loaded saved state information\n");
3447 static void dump_state()
3452 if (!config
->save_state
)
3457 if (!(f
= fopen(STATEFILE
, "w")))
3460 LOG(1, 0, 0, "Dumping state information\n");
3462 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3465 LOG(2, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3466 buf
[0] = ip_pool_size
;
3467 buf
[1] = sizeof(ippoolt
);
3468 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3470 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3473 LOG(2, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3475 buf
[1] = sizeof(tunnelt
);
3476 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3478 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3481 LOG(2, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3482 buf
[0] = MAXSESSION
;
3483 buf
[1] = sizeof(sessiont
);
3484 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3486 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3494 LOG(0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3498 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
)
3501 *challenge_response
= NULL
;
3503 if (!*config
->l2tpsecret
)
3505 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3509 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
3511 *challenge_response
= (char *)calloc(17, 1);
3514 MD5Update(&ctx
, &id
, 1);
3515 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3516 MD5Update(&ctx
, challenge
, challenge_length
);
3517 MD5Final(*challenge_response
, &ctx
);
3522 static int facility_value(char *name
)
3525 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3527 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3528 return facilitynames
[i
].c_val
;
3533 static void update_config()
3536 static int timeout
= 0;
3537 static int interval
= 0;
3547 if (*config
->log_filename
)
3549 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3551 char *p
= config
->log_filename
+ 7;
3554 openlog("l2tpns", LOG_PID
, facility_value(p
));
3558 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3560 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3562 fseek(log_stream
, 0, SEEK_END
);
3563 setbuf(log_stream
, NULL
);
3567 log_stream
= stderr
;
3568 setbuf(log_stream
, NULL
);
3574 log_stream
= stderr
;
3575 setbuf(log_stream
, NULL
);
3580 config
->numradiusservers
= 0;
3581 for (i
= 0; i
< MAXRADSERVER
; i
++)
3582 if (config
->radiusserver
[i
])
3584 config
->numradiusservers
++;
3585 // Set radius port: if not set, take the port from the
3586 // first radius server. For the first radius server,
3587 // take the #defined default value from l2tpns.h
3589 // test twice, In case someone works with
3590 // a secondary radius server without defining
3591 // a primary one, this will work even then.
3592 if (i
>0 && !config
->radiusport
[i
])
3593 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3594 if (!config
->radiusport
[i
])
3595 config
->radiusport
[i
] = RADPORT
;
3598 if (!config
->numradiusservers
)
3599 LOG(0, 0, 0, "No RADIUS servers defined!\n");
3601 config
->num_radfds
= 2 << RADIUS_SHIFT
;
3604 for (i
= 0; i
< MAXPLUGINS
; i
++)
3606 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3609 if (*config
->plugins
[i
])
3612 add_plugin(config
->plugins
[i
]);
3614 else if (*config
->old_plugins
[i
])
3617 remove_plugin(config
->old_plugins
[i
]);
3620 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3621 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
3622 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3623 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3624 if (!*config
->cluster_interface
)
3625 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3627 if (!config
->cluster_hb_interval
)
3628 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3630 if (!config
->cluster_hb_timeout
)
3631 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3633 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3635 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3636 // late, ensure we're sufficiently larger than that
3637 int t
= 4 * config
->cluster_hb_interval
+ 11;
3639 if (config
->cluster_hb_timeout
< t
)
3641 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3642 config
->cluster_hb_timeout
= t
;
3645 // Push timing changes to the slaves immediately if we're the master
3646 if (config
->cluster_iam_master
)
3647 cluster_heartbeat();
3649 interval
= config
->cluster_hb_interval
;
3650 timeout
= config
->cluster_hb_timeout
;
3654 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3657 if ((f
= fopen(config
->pid_file
, "w")))
3659 fprintf(f
, "%d\n", getpid());
3661 config
->wrote_pid
= 1;
3665 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3669 config
->reload_config
= 0;
3672 static void read_config_file()
3676 if (!config
->config_file
) return;
3677 if (!(f
= fopen(config
->config_file
, "r")))
3679 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3683 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
3685 LOG(3, 0, 0, "Done reading config file\n");
3690 int sessionsetup(tunnelidt t
, sessionidt s
)
3692 // A session now exists, set it up
3698 CSTAT(call_sessionsetup
);
3700 LOG(3, s
, t
, "Doing session setup for session\n");
3702 if (!session
[s
].ip
|| session
[s
].ip
== 0xFFFFFFFE)
3704 assign_ip_address(s
);
3707 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3708 sessionshutdown(s
, "No IP addresses available");
3711 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
3712 fmtaddr(htonl(session
[s
].ip
), 0));
3716 // Make sure this is right
3717 session
[s
].tunnel
= t
;
3719 // zap old sessions with same IP and/or username
3720 // Don't kill gardened sessions - doing so leads to a DoS
3721 // from someone who doesn't need to know the password
3724 user
= session
[s
].user
;
3725 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3727 if (i
== s
) continue;
3728 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3729 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3730 sessionkill(i
, "Duplicate session for users");
3737 // Add the route for this session.
3738 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3740 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
3741 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
3744 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
3747 // Static IPs need to be routed if not already
3748 // convered by a Framed-Route. Anything else is part
3749 // of the IP address pool and is already routed, it
3750 // just needs to be added to the IP cache.
3751 if (session
[s
].ip_pool_index
== -1) // static ip
3753 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
3756 cache_ipmap(session
[s
].ip
, s
);
3759 if (!session
[s
].unique_id
)
3761 // did this session just finish radius?
3762 LOG(3, s
, t
, "Sending initial IPCP to client\n");
3764 session
[s
].unique_id
= ++last_id
;
3767 // Run the plugin's against this new session.
3769 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3770 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3773 // Allocate TBFs if throttled
3774 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3775 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3777 session
[s
].last_packet
= time_now
;
3779 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
3780 fmtaddr(htonl(session
[s
].ip
), 0),
3781 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
3783 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3785 return 1; // RADIUS OK and IP allocated, done...
3789 // This session just got dropped on us by the master or something.
3790 // Make sure our tables up up to date...
3792 int load_session(sessionidt s
, sessiont
*new)
3798 if (new->ip_pool_index
>= MAXIPPOOL
||
3799 new->tunnel
>= MAXTUNNEL
)
3801 LOG(0, s
, 0, "Strange session update received!\n");
3802 // FIXME! What to do here?
3807 // Ok. All sanity checks passed. Now we're committed to
3808 // loading the new session.
3811 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3813 // See if routes/ip cache need updating
3814 if (new->ip
!= session
[s
].ip
)
3817 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3818 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
3819 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
3827 // remove old routes...
3828 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3830 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
3831 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
3834 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
3840 if (session
[s
].ip_pool_index
== -1) // static IP
3842 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
3844 else // It's part of the IP pool, remove it manually.
3845 uncache_ipmap(session
[s
].ip
);
3850 // add new routes...
3851 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
3853 if ((new->ip
& new->route
[i
].mask
) ==
3854 (new->route
[i
].ip
& new->route
[i
].mask
))
3857 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
3863 // If there's a new one, add it.
3864 if (new->ip_pool_index
== -1)
3866 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
3869 cache_ipmap(new->ip
, s
);
3874 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
3876 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %d\n", (int) new->filter_in
);
3880 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
3882 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %d\n", (int) new->filter_out
);
3883 new->filter_out
= 0;
3886 if (new->filter_in
!= session
[s
].filter_in
)
3888 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
3889 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
3892 if (new->filter_out
!= session
[s
].filter_out
)
3894 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
3895 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
3898 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
3899 // for walking the sessions to forward byte counts to the master.
3900 config
->cluster_highest_sessionid
= s
;
3902 // TEMP: old session struct used a uint32_t to define the throttle
3903 // speed for both up/down, new uses a uint16_t for each. Deal with
3904 // sessions from an old master for migration.
3905 if (new->throttle_out
== 0 && new->tbf_out
)
3906 new->throttle_out
= new->throttle_in
;
3908 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
3910 // Do fixups into address pool.
3911 if (new->ip_pool_index
!= -1)
3912 fix_address_pool(s
);
3917 static void initplugins()
3921 loaded_plugins
= ll_init();
3922 // Initialize the plugins to nothing
3923 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
3924 plugins
[i
] = ll_init();
3927 static void *open_plugin(char *plugin_name
, int load
)
3929 char path
[256] = "";
3931 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
3932 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
3933 return dlopen(path
, RTLD_NOW
);
3936 // plugin callback to get a config value
3937 static void *getconfig(char *key
, enum config_typet type
)
3941 for (i
= 0; config_values
[i
].key
; i
++)
3943 if (!strcmp(config_values
[i
].key
, key
))
3945 if (config_values
[i
].type
== type
)
3946 return ((void *) config
) + config_values
[i
].offset
;
3948 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
3949 key
, type
, config_values
[i
].type
);
3955 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
3959 static int add_plugin(char *plugin_name
)
3961 static struct pluginfuncs funcs
= {
3966 sessiontbysessionidt
,
3967 sessionidtbysessiont
,
3973 cluster_send_session
,
3976 void *p
= open_plugin(plugin_name
, 1);
3977 int (*initfunc
)(struct pluginfuncs
*);
3982 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
3986 if (ll_contains(loaded_plugins
, p
))
3989 return 0; // already loaded
3993 int *v
= dlsym(p
, "plugin_api_version");
3994 if (!v
|| *v
!= PLUGIN_API_VERSION
)
3996 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
4002 if ((initfunc
= dlsym(p
, "plugin_init")))
4004 if (!initfunc(&funcs
))
4006 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
4012 ll_push(loaded_plugins
, p
);
4014 for (i
= 0; i
< max_plugin_functions
; i
++)
4017 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4019 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
4020 ll_push(plugins
[i
], x
);
4024 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
4028 static void run_plugin_done(void *plugin
)
4030 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
4036 static int remove_plugin(char *plugin_name
)
4038 void *p
= open_plugin(plugin_name
, 0);
4044 if (ll_contains(loaded_plugins
, p
))
4047 for (i
= 0; i
< max_plugin_functions
; i
++)
4050 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4051 ll_delete(plugins
[i
], x
);
4054 ll_delete(loaded_plugins
, p
);
4060 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
4064 int run_plugins(int plugin_type
, void *data
)
4066 int (*func
)(void *data
);
4068 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
4069 return PLUGIN_RET_ERROR
;
4071 ll_reset(plugins
[plugin_type
]);
4072 while ((func
= ll_next(plugins
[plugin_type
])))
4076 if (r
!= PLUGIN_RET_OK
)
4077 return r
; // stop here
4080 return PLUGIN_RET_OK
;
4083 static void plugins_done()
4087 ll_reset(loaded_plugins
);
4088 while ((p
= ll_next(loaded_plugins
)))
4092 static void processcontrol(uint8_t * buf
, int len
, struct sockaddr_in
*addr
, int alen
)
4094 struct nsctl request
;
4095 struct nsctl response
;
4096 int type
= unpack_control(&request
, buf
, len
);
4100 if (log_stream
&& config
->debug
>= 4)
4104 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4105 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
4109 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4110 dump_control(&request
, log_stream
);
4116 case NSCTL_REQ_LOAD
:
4117 if (request
.argc
!= 1)
4119 response
.type
= NSCTL_RES_ERR
;
4121 response
.argv
[0] = "name of plugin required";
4123 else if ((r
= add_plugin(request
.argv
[0])) < 1)
4125 response
.type
= NSCTL_RES_ERR
;
4127 response
.argv
[0] = !r
4128 ? "plugin already loaded"
4129 : "error loading plugin";
4133 response
.type
= NSCTL_RES_OK
;
4139 case NSCTL_REQ_UNLOAD
:
4140 if (request
.argc
!= 1)
4142 response
.type
= NSCTL_RES_ERR
;
4144 response
.argv
[0] = "name of plugin required";
4146 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
4148 response
.type
= NSCTL_RES_ERR
;
4150 response
.argv
[0] = !r
4151 ? "plugin not loaded"
4152 : "plugin not found";
4156 response
.type
= NSCTL_RES_OK
;
4162 case NSCTL_REQ_HELP
:
4163 response
.type
= NSCTL_RES_OK
;
4166 ll_reset(loaded_plugins
);
4167 while ((p
= ll_next(loaded_plugins
)))
4169 char **help
= dlsym(p
, "plugin_control_help");
4170 while (response
.argc
< 0xff && help
&& *help
)
4171 response
.argv
[response
.argc
++] = *help
++;
4176 case NSCTL_REQ_CONTROL
:
4178 struct param_control param
= {
4179 config
->cluster_iam_master
,
4186 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4188 if (r
== PLUGIN_RET_ERROR
)
4190 response
.type
= NSCTL_RES_ERR
;
4192 response
.argv
[0] = param
.additional
4194 : "error returned by plugin";
4196 else if (r
== PLUGIN_RET_NOTMASTER
)
4198 static char msg
[] = "must be run on master: 000.000.000.000";
4200 response
.type
= NSCTL_RES_ERR
;
4202 if (config
->cluster_master_address
)
4204 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
4205 response
.argv
[0] = msg
;
4209 response
.argv
[0] = "must be run on master: none elected";
4212 else if (!(param
.response
& NSCTL_RESPONSE
))
4214 response
.type
= NSCTL_RES_ERR
;
4216 response
.argv
[0] = param
.response
4217 ? "unrecognised response value from plugin"
4218 : "unhandled action";
4222 response
.type
= param
.response
;
4224 if (param
.additional
)
4227 response
.argv
[0] = param
.additional
;
4235 response
.type
= NSCTL_RES_ERR
;
4237 response
.argv
[0] = "error unpacking control packet";
4240 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4243 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4247 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4250 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4251 if (log_stream
&& config
->debug
>= 4)
4253 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4254 dump_control(&response
, log_stream
);
4258 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4259 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
4264 static tunnelidt
new_tunnel()
4267 for (i
= 1; i
< MAXTUNNEL
; i
++)
4269 if (tunnel
[i
].state
== TUNNELFREE
)
4271 LOG(4, 0, i
, "Assigning tunnel ID %d\n", i
);
4272 if (i
> config
->cluster_highest_tunnelid
)
4273 config
->cluster_highest_tunnelid
= i
;
4277 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4282 // We're becoming the master. Do any required setup..
4284 // This is principally telling all the plugins that we're
4285 // now a master, and telling them about all the sessions
4286 // that are active too..
4288 void become_master(void)
4291 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4293 // running a bunch of iptables commands is slow and can cause
4294 // the master to drop tunnels on takeover--kludge around the
4295 // problem by forking for the moment (note: race)
4296 if (!fork_and_close())
4298 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4300 if (!session
[s
].tunnel
) // Not an in-use session.
4303 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4309 for (i
= 0; i
< config
->num_radfds
; i
++)
4311 FD_SET(radfds
[i
], &readset
);
4312 if (radfds
[i
] > readset_n
)
4313 readset_n
= radfds
[i
];
4317 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4323 if (CLI_HELP_REQUESTED
)
4324 return CLI_HELP_NO_ARGS
;
4327 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4329 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4332 if (!session
[s
].tunnel
)
4335 idle
= time_now
- session
[s
].last_packet
;
4336 idle
/= 5 ; // In multiples of 5 seconds.
4346 for (i
= 0; i
< 63; ++i
)
4348 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4350 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4351 cli_print(cli
, "%d total sessions open.", count
);
4355 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4361 if (CLI_HELP_REQUESTED
)
4362 return CLI_HELP_NO_ARGS
;
4365 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4367 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4370 if (!session
[s
].tunnel
)
4373 d
= time_now
- session
[s
].opened
;
4376 while (d
> 1 && open
< 32)
4386 for (i
= 0; i
< 30; ++i
)
4388 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4391 cli_print(cli
, "%d total sessions open.", count
);
4397 * This unencodes the AVP using the L2TP CHAP secret and the
4398 * previously stored random vector. It replaces the hidden data with
4399 * the cleartext data and returns the length of the cleartext data
4400 * (including the AVP "header" of 6 bytes).
4402 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4404 static int unhide_avp(uint8_t *avp
, tunnelidt t
, sessionidt s
, uint16_t length
)
4409 uint8_t working_vector
[16];
4410 uint16_t hidden_length
;
4415 // Find the AVP type.
4416 type
[0] = *(avp
+ 4);
4417 type
[1] = *(avp
+ 5);
4419 // Line up with the hidden data
4420 cursor
= output
= avp
+ 6;
4422 // Compute initial pad
4424 MD5Update(&ctx
, type
, 2);
4425 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4426 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4427 MD5Final(digest
, &ctx
);
4429 // Get hidden length
4430 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4432 // Keep these for later use
4433 working_vector
[0] = *cursor
;
4434 working_vector
[1] = *(cursor
+ 1);
4437 if (hidden_length
> length
- 8)
4439 LOG(1, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4443 /* Decrypt remainder */
4445 todo
= hidden_length
;
4448 working_vector
[done
] = *cursor
;
4449 *output
= digest
[done
] ^ *cursor
;
4454 if (done
== 16 && todo
)
4456 // Compute new digest
4459 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4460 MD5Update(&ctx
, &working_vector
, 16);
4461 MD5Final(digest
, &ctx
);
4465 return hidden_length
+ 6;
4468 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
4472 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
4473 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
4474 case FILTER_PORT_OP_GT
: return port
> p
->port
;
4475 case FILTER_PORT_OP_LT
: return port
< p
->port
;
4476 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
4482 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
4486 case FILTER_FLAG_OP_ANY
:
4487 return (flags
& sflags
) || (~flags
& cflags
);
4489 case FILTER_FLAG_OP_ALL
:
4490 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
4492 case FILTER_FLAG_OP_EST
:
4493 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
4499 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
4501 uint16_t frag_offset
;
4505 uint16_t src_port
= 0;
4506 uint16_t dst_port
= 0;
4508 ip_filter_rulet
*rule
;
4510 if (len
< 20) // up to end of destination address
4513 if ((*buf
>> 4) != 4) // IPv4
4516 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
4518 src_ip
= *(in_addr_t
*) (buf
+ 12);
4519 dst_ip
= *(in_addr_t
*) (buf
+ 16);
4521 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
4523 int l
= (buf
[0] & 0xf) * 4; // length of IP header
4524 if (len
< l
+ 4) // ports
4527 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
4528 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
4529 if (proto
== IPPROTO_TCP
)
4531 if (len
< l
+ 14) // flags
4534 flags
= buf
[l
+ 13] & 0x3f;
4538 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
4540 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
4543 if (rule
->src_wild
!= INADDR_BROADCAST
&&
4544 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
4547 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
4548 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
4553 if (!rule
->frag
|| rule
->action
== FILTER_ACTION_DENY
)
4561 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
4563 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
4566 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
4569 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
4570 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
4577 return rule
->action
== FILTER_ACTION_PERMIT
;