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.56 2004/11/25 02:49:18 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 struct 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 u32 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 u32 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 u32 udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
80 static u32 eth_rx
= 0, eth_rx_pkt
= 0;
83 static u32 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(struct configt, MEMBER), membersize(struct configt, MEMBER), TYPE }
93 struct config_descriptt config_values
[] = {
94 CONFIG("debug", debug
, INT
),
95 CONFIG("log_file", log_filename
, STRING
),
96 CONFIG("pid_file", pid_file
, STRING
),
97 CONFIG("l2tp_secret", l2tpsecret
, STRING
),
98 CONFIG("primary_dns", default_dns1
, IP
),
99 CONFIG("secondary_dns", default_dns2
, IP
),
100 CONFIG("save_state", save_state
, BOOL
),
101 CONFIG("primary_radius", radiusserver
[0], IP
),
102 CONFIG("secondary_radius", radiusserver
[1], IP
),
103 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
104 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
105 CONFIG("radius_accounting", radius_accounting
, BOOL
),
106 CONFIG("radius_secret", radiussecret
, STRING
),
107 CONFIG("bind_address", bind_address
, IP
),
108 CONFIG("peer_address", peer_address
, IP
),
109 CONFIG("send_garp", send_garp
, BOOL
),
110 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
111 CONFIG("throttle_buckets", num_tbfs
, INT
),
112 CONFIG("accounting_dir", accounting_dir
, STRING
),
113 CONFIG("setuid", target_uid
, INT
),
114 CONFIG("dump_speed", dump_speed
, BOOL
),
115 CONFIG("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
, IP
),
121 CONFIG("cluster_interface", cluster_interface
, STRING
),
122 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
123 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
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 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
145 sessiont
*session
= NULL
; // Array of session structures.
146 sessioncountt
*sess_count
= NULL
; // Array of partial per-session traffic counters.
147 radiust
*radius
= NULL
; // Array of radius structures.
148 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
149 static controlt
*controlfree
= 0;
150 struct Tstats
*_statistics
= NULL
;
152 struct Tringbuffer
*ringbuffer
= NULL
;
155 static void cache_ipmap(ipt ip
, int s
);
156 static void uncache_ipmap(ipt ip
);
157 static void free_ip_address(sessionidt s
);
158 static void dump_acct_info(void);
159 static void sighup_handler(int sig
);
160 static void sigalrm_handler(int sig
);
161 static void sigterm_handler(int sig
);
162 static void sigquit_handler(int sig
);
163 static void sigchild_handler(int sig
);
164 static void read_state(void);
165 static void dump_state(void);
166 static void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
);
167 static void update_config(void);
168 static void read_config_file(void);
169 static void initplugins(void);
170 static int add_plugin(char *plugin_name
);
171 static int remove_plugin(char *plugin_name
);
172 static void plugins_done(void);
173 static void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
, int alen
);
174 static tunnelidt
new_tunnel(void);
175 static int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
);
177 // return internal time (10ths since process startup)
178 static clockt
now(void)
182 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
185 // work out a retry time based on try number
186 // This is a straight bounded exponential backoff.
187 // Maximum re-try time is 32 seconds. (2^5).
188 clockt
backoff(u8
try)
190 if (try > 5) try = 5; // max backoff
191 return now() + 10 * (1 << try);
196 // Log a debug message. Typically called vias LOG macro
198 void _log(int level
, ipt address
, sessionidt s
, tunnelidt t
, const char *format
, ...)
200 static char message
[65536] = {0};
201 static char message2
[65536] = {0};
207 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
208 ringbuffer
->tail
= 0;
209 if (ringbuffer
->tail
== ringbuffer
->head
)
210 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
211 ringbuffer
->head
= 0;
213 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
214 ringbuffer
->buffer
[ringbuffer
->tail
].address
= address
;
215 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
216 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
217 va_start(ap
, format
);
218 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
223 if (config
->debug
< level
) return;
225 va_start(ap
, format
);
228 vsnprintf(message2
, 65535, format
, ap
);
229 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
230 fprintf(log_stream
, "%s", message
);
234 vsnprintf(message2
, 65535, format
, ap
);
235 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
236 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
241 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
244 const u8
*d
= (const u8
*)data
;
246 if (config
->debug
< level
) return;
248 // No support for _log_hex to syslog
251 _log(level
, 0, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
252 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
254 for (i
= 0; i
< maxsize
; )
256 fprintf(log_stream
, "%4X: ", i
);
257 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
259 fprintf(log_stream
, "%02X ", d
[j
]);
261 fputs(": ", log_stream
);
264 for (; j
< i
+ 16; j
++)
266 fputs(" ", log_stream
);
268 fputs(": ", log_stream
);
271 fputs(" ", log_stream
);
272 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
274 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
275 fputc(d
[j
], log_stream
);
277 fputc('.', log_stream
);
280 fputs(" ", log_stream
);
284 fputs("\n", log_stream
);
288 setbuf(log_stream
, NULL
);
295 // This adds it to the routing table, advertises it
296 // via BGP if enabled, and stuffs it into the
297 // 'sessionbyip' cache.
299 // 'ip' and 'mask' must be in _host_ order.
301 static void routeset(sessionidt s
, ipt ip
, ipt mask
, ipt gw
, u8 add
)
306 if (!mask
) mask
= 0xffffffff;
308 ip
&= mask
; // Force the ip to be the first one in the route.
310 memset(&r
, 0, sizeof(r
));
311 r
.rt_dev
= config
->tundevice
;
312 r
.rt_dst
.sa_family
= AF_INET
;
313 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
314 r
.rt_gateway
.sa_family
= AF_INET
;
315 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
316 r
.rt_genmask
.sa_family
= AF_INET
;
317 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
318 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
320 r
.rt_flags
|= RTF_GATEWAY
;
321 else if (mask
== 0xffffffff)
322 r
.rt_flags
|= RTF_HOST
;
324 LOG(1, ip
, 0, 0, "Route %s %u.%u.%u.%u/%u.%u.%u.%u %u.%u.%u.%u\n",
326 ip
>> 24, ip
>> 16 & 0xff, ip
>> 8 & 0xff, ip
& 0xff,
327 mask
>> 24, mask
>> 16 & 0xff, mask
>> 8 & 0xff, mask
& 0xff,
328 gw
>> 24, gw
>> 16 & 0xff, gw
>> 8 & 0xff, gw
& 0xff);
330 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
331 LOG(0, 0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
335 bgp_add_route(htonl(ip
), htonl(mask
));
337 bgp_del_route(htonl(ip
), htonl(mask
));
340 // Add/Remove the IPs to the 'sessionbyip' cache.
341 // Note that we add the zero address in the case of
342 // a network route. Roll on CIDR.
344 // Note that 's == 0' implies this is the address pool.
345 // We still cache it here, because it will pre-fill
346 // the malloc'ed tree.
350 if (!add
) // Are we deleting a route?
351 s
= 0; // Caching the session as '0' is the same as uncaching.
353 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
359 // Set up TUN interface
360 static void inittun(void)
363 struct sockaddr_in sin
= {0};
364 memset(&ifr
, 0, sizeof(ifr
));
365 ifr
.ifr_flags
= IFF_TUN
;
367 tunfd
= open(TUNDEVICE
, O_RDWR
);
370 LOG(0, 0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
374 int flags
= fcntl(tunfd
, F_GETFL
, 0);
375 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
377 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
379 LOG(0, 0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
382 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
383 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
384 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
386 sin
.sin_family
= AF_INET
;
387 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
388 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
390 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
392 LOG(0, 0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
395 /* Bump up the qlen to deal with bursts from the network */
397 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
399 LOG(0, 0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
402 ifr
.ifr_flags
= IFF_UP
;
403 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
405 LOG(0, 0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
411 static void initudp(void)
414 struct sockaddr_in addr
;
417 memset(&addr
, 0, sizeof(addr
));
418 addr
.sin_family
= AF_INET
;
419 addr
.sin_port
= htons(L2TPPORT
);
420 addr
.sin_addr
.s_addr
= config
->bind_address
;
421 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
422 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
424 int flags
= fcntl(udpfd
, F_GETFL
, 0);
425 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
427 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
429 LOG(0, 0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
432 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
435 memset(&addr
, 0, sizeof(addr
));
436 addr
.sin_family
= AF_INET
;
437 addr
.sin_port
= htons(NSCTL_PORT
);
438 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
439 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
440 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
442 LOG(0, 0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
448 // Find session by IP, < 1 for not found
450 // Confusingly enough, this 'ip' must be
451 // in _network_ order. This being the common
452 // case when looking it up from IP packet headers.
454 // We actually use this cache for two things.
455 // #1. For used IP addresses, this maps to the
456 // session ID that it's used by.
457 // #2. For un-used IP addresses, this maps to the
458 // index into the pool table that contains that
462 static int lookup_ipmap(ipt ip
)
465 char **d
= (char **) ip_hash
;
468 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
469 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
470 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
472 s
= (ipt
) d
[(size_t) *a
];
476 sessionidt
sessionbyip(ipt ip
)
478 int s
= lookup_ipmap(ip
);
479 CSTAT(call_sessionbyip
);
481 if (s
> 0 && s
< MAXSESSION
&& session
[s
].tunnel
)
487 // Take an IP address in HOST byte order and
488 // add it to the sessionid by IP cache.
490 // (It's actually cached in network order)
492 static void cache_ipmap(ipt ip
, int s
)
494 ipt nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char*)(&ip))[0]
496 char **d
= (char **) ip_hash
;
499 for (i
= 0; i
< 3; i
++)
501 if (!d
[(size_t) a
[i
]])
503 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof (void *))))
507 d
= (char **) d
[(size_t) a
[i
]];
510 d
[(size_t) a
[3]] = (char *)((int)s
);
513 LOG(4, ip
, s
, session
[s
].tunnel
, "Caching ip address %s\n", inet_toa(nip
));
515 LOG(4, ip
, 0, 0, "Un-caching ip address %s\n", inet_toa(nip
));
516 // else a map to an ip pool index.
519 static void uncache_ipmap(ipt ip
)
521 cache_ipmap(ip
, 0); // Assign it to the NULL session.
525 // CLI list to dump current ipcache.
527 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
529 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
533 if (CLI_HELP_REQUESTED
)
534 return CLI_HELP_NO_ARGS
;
536 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
538 for (i
= 0; i
< 256; ++i
)
543 for (j
= 0; j
< 256; ++j
)
548 for (k
= 0; k
< 256; ++k
)
553 for (l
= 0; l
< 256; ++l
)
557 cli_print(cli
, "%7d %d.%d.%d.%d", (int) g
[l
], i
, j
, k
, l
);
563 cli_print(cli
, "%d entries in cache", count
);
568 // Find session by username, 0 for not found
569 // walled garden users aren't authenticated, so the username is
570 // reasonably useless. Ignore them to avoid incorrect actions
572 // This is VERY inefficent. Don't call it often. :)
574 sessionidt
sessionbyuser(char *username
)
577 CSTAT(call_sessionbyuser
);
579 for (s
= 1; s
< MAXSESSION
; ++s
)
581 if (session
[s
].walled_garden
)
582 continue; // Skip walled garden users.
584 if (!strncmp(session
[s
].user
, username
, 128))
588 return 0; // Not found.
591 void send_garp(ipt ip
)
597 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
600 LOG(0, 0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
603 memset(&ifr
, 0, sizeof(ifr
));
604 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
605 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
607 LOG(0, 0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
611 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
612 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
614 LOG(0, 0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
619 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
622 // Find session by username, 0 for not found
623 static sessiont
*sessiontbysessionidt(sessionidt s
)
625 if (!s
|| s
> MAXSESSION
) return NULL
;
629 static sessionidt
sessionidtbysessiont(sessiont
*s
)
631 sessionidt val
= s
-session
;
632 if (s
< session
|| val
> MAXSESSION
) return 0;
636 // actually send a control message for a specific tunnel
637 void tunnelsend(u8
* buf
, u16 l
, tunnelidt t
)
639 struct sockaddr_in addr
;
641 CSTAT(call_tunnelsend
);
645 static int backtrace_count
= 0;
646 LOG(0, 0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
647 STAT(tunnel_tx_errors
);
648 log_backtrace(backtrace_count
, 5)
654 static int backtrace_count
= 0;
655 LOG(1, 0, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
656 log_backtrace(backtrace_count
, 5)
657 STAT(tunnel_tx_errors
);
661 memset(&addr
, 0, sizeof(addr
));
662 addr
.sin_family
= AF_INET
;
663 *(u32
*) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
664 addr
.sin_port
= htons(tunnel
[t
].port
);
666 // sequence expected, if sequence in message
667 if (*buf
& 0x08) *(u16
*) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
669 // If this is a control message, deal with retries
672 tunnel
[t
].last
= time_now
; // control message sent
673 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
674 if (tunnel
[t
].try > 1)
676 STAT(tunnel_retries
);
677 LOG(3, tunnel
[t
].ip
, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
681 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
683 LOG(0, tunnel
[t
].ip
, ntohs((*(u16
*) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
684 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
685 STAT(tunnel_tx_errors
);
689 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
690 STAT(tunnel_tx_packets
);
691 INC_STAT(tunnel_tx_bytes
, l
);
695 // Tiny helper function to write data to
698 int tun_write(u8
* data
, int size
)
700 return write(tunfd
, data
, size
);
703 // process outgoing (to tunnel) IP
705 static void processipout(u8
* buf
, int len
)
712 char * data
= buf
; // Keep a copy of the originals.
717 CSTAT(call_processipout
);
719 if (len
< MIN_IP_SIZE
)
721 LOG(1, 0, 0, 0, "Short IP, %d bytes\n", len
);
722 STAT(tunnel_tx_errors
);
727 LOG(1, 0, 0, 0, "Oversize IP packet %d bytes\n", len
);
728 STAT(tunnel_tx_errors
);
732 // Skip the tun header
736 // Got an IP header now
737 if (*(u8
*)(buf
) >> 4 != 4)
739 LOG(1, 0, 0, 0, "IP: Don't understand anything except IPv4\n");
743 ip
= *(u32
*)(buf
+ 16);
744 if (!(s
= sessionbyip(ip
)))
746 // Is this a packet for a session that doesn't exist?
747 static int rate
= 0; // Number of ICMP packets we've sent this second.
748 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
750 if (last
!= time_now
)
756 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
758 LOG(4, 0, 0, 0, "IP: Sending ICMP host unreachable to %s\n", inet_toa(*(u32
*)(buf
+ 12)));
759 host_unreachable(*(u32
*)(buf
+ 12), *(u16
*)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
763 t
= session
[s
].tunnel
;
768 // Are we throttling this session?
769 if (config
->cluster_iam_master
)
770 tbf_queue_packet(sp
->tbf_out
, data
, size
);
772 master_throttle_packet(sp
->tbf_out
, data
, size
);
775 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
777 // We are walled-gardening this
778 master_garden_packet(s
, data
, size
);
782 LOG(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
784 // Add on L2TP header
786 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
788 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
791 // Snooping this session, send it to intercept box
792 if (sp
->snoop_ip
&& sp
->snoop_port
)
793 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
795 sp
->cout
+= len
; // byte count
796 sp
->total_cout
+= len
; // byte count
799 sess_count
[s
].cout
+= len
; // To send to master..
803 // Helper routine for the TBF filters.
804 // Used to send queued data in to the user!
806 static void send_ipout(sessionidt s
, u8
*buf
, int len
)
814 if (len
< 0 || len
> MAXETHER
)
816 LOG(1,0,0,0, "Odd size IP packet: %d bytes\n", len
);
820 // Skip the tun header
824 ip
= *(u32
*)(buf
+ 16);
829 t
= session
[s
].tunnel
;
832 LOG(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
834 // Add on L2TP header
836 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
838 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
841 // Snooping this session.
842 if (sp
->snoop_ip
&& sp
->snoop_port
)
843 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
845 sp
->cout
+= len
; // byte count
846 sp
->total_cout
+= len
; // byte count
849 sess_count
[s
].cout
+= len
; // To send to master..
852 // add an AVP (16 bit)
853 static void control16(controlt
* c
, u16 avp
, u16 val
, u8 m
)
855 u16 l
= (m
? 0x8008 : 0x0008);
856 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
857 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
858 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
859 *(u16
*) (c
->buf
+ c
->length
+ 6) = htons(val
);
863 // add an AVP (32 bit)
864 static void control32(controlt
* c
, u16 avp
, u32 val
, u8 m
)
866 u16 l
= (m
? 0x800A : 0x000A);
867 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
868 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
869 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
870 *(u32
*) (c
->buf
+ c
->length
+ 6) = htonl(val
);
874 // add an AVP (32 bit)
875 static void controls(controlt
* c
, u16 avp
, char *val
, u8 m
)
877 u16 l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
878 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
879 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
880 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
881 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
882 c
->length
+= 6 + strlen(val
);
886 static void controlb(controlt
* c
, u16 avp
, char *val
, unsigned int len
, u8 m
)
888 u16 l
= ((m
? 0x8000 : 0) + len
+ 6);
889 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
890 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
891 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
892 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
893 c
->length
+= 6 + len
;
896 // new control connection
897 static controlt
*controlnew(u16 mtype
)
901 c
= malloc(sizeof(controlt
));
905 controlfree
= c
->next
;
909 *(u16
*) (c
->buf
+ 0) = htons(0xC802); // flags/ver
911 control16(c
, 0, mtype
, 1);
915 // send zero block if nothing is waiting
917 static void controlnull(tunnelidt t
)
920 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
923 *(u16
*) (buf
+ 0) = htons(0xC802); // flags/ver
924 *(u16
*) (buf
+ 2) = htons(12); // length
925 *(u16
*) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
926 *(u16
*) (buf
+ 6) = htons(0); // session
927 *(u16
*) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
928 *(u16
*) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
929 tunnelsend(buf
, 12, t
);
932 // add a control message to a tunnel, and send if within window
933 static void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
935 *(u16
*) (c
->buf
+ 2) = htons(c
->length
); // length
936 *(u16
*) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
937 *(u16
*) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
938 *(u16
*) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
939 tunnel
[t
].ns
++; // advance sequence
940 // link in message in to queue
941 if (tunnel
[t
].controlc
)
942 tunnel
[t
].controle
->next
= c
;
944 tunnel
[t
].controls
= c
;
945 tunnel
[t
].controle
= c
;
946 tunnel
[t
].controlc
++;
947 // send now if space in window
948 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
950 tunnel
[t
].try = 0; // first send
951 tunnelsend(c
->buf
, c
->length
, t
);
956 // Throttle or Unthrottle a session
958 // Throttle the data from/to through a session to no more than
959 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
962 // If either value is -1, the current value is retained for that
965 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
967 if (!session
[s
].tunnel
)
968 return; // No-one home.
970 if (!*session
[s
].user
)
971 return; // User not logged in
975 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
976 if (session
[s
].tbf_in
)
977 free_tbf(session
[s
].tbf_in
);
980 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
982 session
[s
].tbf_in
= 0;
984 session
[s
].throttle_in
= rate_in
;
989 int bytes
= rate_out
* 1024 / 8;
990 if (session
[s
].tbf_out
)
991 free_tbf(session
[s
].tbf_out
);
994 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
996 session
[s
].tbf_out
= 0;
998 session
[s
].throttle_out
= rate_out
;
1002 // start tidy shutdown of session
1003 void sessionshutdown(sessionidt s
, char *reason
)
1005 int walled_garden
= session
[s
].walled_garden
;
1008 CSTAT(call_sessionshutdown
);
1010 if (!session
[s
].tunnel
)
1012 LOG(3, session
[s
].ip
, s
, session
[s
].tunnel
, "Called sessionshutdown on a session with no tunnel.\n");
1013 return; // not a live session
1016 if (!session
[s
].die
)
1018 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1019 LOG(2, 0, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1020 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1023 // RADIUS Stop message
1024 if (session
[s
].opened
&& !walled_garden
&& !session
[s
].die
)
1026 u16 r
= session
[s
].radius
;
1029 if (!(r
= radiusnew(s
)))
1031 LOG(1, 0, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1032 STAT(radius_overflow
);
1037 for (n
= 0; n
< 15; n
++)
1038 radius
[r
].auth
[n
] = rand();
1041 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1042 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1046 { // IP allocated, clear and unroute
1049 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1051 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1052 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1055 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1056 session
[s
].route
[r
].ip
= 0;
1059 if (session
[s
].ip_pool_index
== -1) // static ip
1061 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1068 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1069 throttle_session(s
, 0, 0);
1072 controlt
*c
= controlnew(14); // sending CDN
1073 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1074 control16(c
, 14, s
, 1); // assigned session (our end)
1075 controladd(c
, session
[s
].tunnel
, s
); // send the message
1078 if (!session
[s
].die
)
1079 session
[s
].die
= now() + 150; // Clean up in 15 seconds
1081 cluster_send_session(s
);
1084 void sendipcp(tunnelidt t
, sessionidt s
)
1087 u16 r
= session
[s
].radius
;
1090 CSTAT(call_sendipcp
);
1095 if (radius
[r
].state
!= RADIUSIPCP
)
1097 radius
[r
].state
= RADIUSIPCP
;
1101 radius
[r
].retry
= backoff(radius
[r
].try++);
1102 if (radius
[r
].try > 10)
1104 radiusclear(r
, s
); // Clear radius session.
1105 sessionshutdown(s
, "No reply on IPCP");
1109 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1113 q
[1] = r
<< RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1114 *(u16
*) (q
+ 2) = htons(10);
1117 *(u32
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1118 config
->bind_address
? config
->bind_address
:
1119 my_address
; // send my IP
1121 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1122 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1125 // kill a session now
1126 static void sessionkill(sessionidt s
, char *reason
)
1129 CSTAT(call_sessionkill
);
1131 session
[s
].die
= now();
1132 sessionshutdown(s
, reason
); // close radius/routes, etc.
1133 if (session
[s
].radius
)
1134 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1136 LOG(2, 0, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1138 memset(&session
[s
], 0, sizeof(session
[s
]));
1139 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1140 session
[s
].next
= sessionfree
;
1142 cli_session_actions
[s
].action
= 0;
1143 cluster_send_session(s
);
1146 static void tunnelclear(tunnelidt t
)
1149 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1150 tunnel
[t
].state
= TUNNELFREE
;
1153 // kill a tunnel now
1154 static void tunnelkill(tunnelidt t
, char *reason
)
1159 CSTAT(call_tunnelkill
);
1161 tunnel
[t
].state
= TUNNELDIE
;
1163 // free control messages
1164 while ((c
= tunnel
[t
].controls
))
1166 controlt
* n
= c
->next
;
1167 tunnel
[t
].controls
= n
;
1168 tunnel
[t
].controlc
--;
1169 c
->next
= controlfree
;
1173 for (s
= 1; s
< MAXSESSION
; s
++)
1174 if (session
[s
].tunnel
== t
)
1175 sessionkill(s
, reason
);
1179 LOG(1, 0, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1180 cli_tunnel_actions
[s
].action
= 0;
1181 cluster_send_tunnel(t
);
1184 // shut down a tunnel cleanly
1185 static void tunnelshutdown(tunnelidt t
, char *reason
)
1189 CSTAT(call_tunnelshutdown
);
1191 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1193 // never set up, can immediately kill
1194 tunnelkill(t
, reason
);
1197 LOG(1, 0, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1200 for (s
= 1; s
< MAXSESSION
; s
++)
1201 if (session
[s
].tunnel
== t
)
1202 sessionshutdown(s
, reason
);
1204 tunnel
[t
].state
= TUNNELDIE
;
1205 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
1206 cluster_send_tunnel(t
);
1207 // TBA - should we wait for sessions to stop?
1209 controlt
*c
= controlnew(4); // sending StopCCN
1210 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message
1211 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1212 controladd(c
, t
, 0); // send the message
1216 // read and process packet on tunnel (UDP)
1217 void processudp(u8
* buf
, int len
, struct sockaddr_in
*addr
)
1219 char *chapresponse
= NULL
;
1220 u16 l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1224 CSTAT(call_processudp
);
1228 LOG_HEX(5, "UDP Data", buf
, len
);
1229 STAT(tunnel_rx_packets
);
1230 INC_STAT(tunnel_rx_bytes
, len
);
1233 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Short UDP, %d bytes\n", len
);
1234 STAT(tunnel_rx_errors
);
1237 if ((buf
[1] & 0x0F) != 2)
1239 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1240 STAT(tunnel_rx_errors
);
1245 l
= ntohs(*(u16
*) p
);
1248 t
= ntohs(*(u16
*) p
);
1250 s
= ntohs(*(u16
*) p
);
1252 if (s
>= MAXSESSION
)
1254 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid session ID\n");
1255 STAT(tunnel_rx_errors
);
1260 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid tunnel ID\n");
1261 STAT(tunnel_rx_errors
);
1266 ns
= ntohs(*(u16
*) p
);
1268 nr
= ntohs(*(u16
*) p
);
1273 u16 o
= ntohs(*(u16
*) p
);
1278 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad length %d>%d\n", (p
- buf
), l
);
1279 STAT(tunnel_rx_errors
);
1285 u16 message
= 0xFFFF; // message type
1287 u8 mandatorymessage
= 0;
1288 u8 chap
= 0; // if CHAP being used
1289 u16 asession
= 0; // assigned session
1290 u32 amagic
= 0; // magic number
1291 u8 aflags
= 0; // flags from last LCF
1292 u16 version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1293 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1294 char called
[MAXTEL
] = ""; // called number
1295 char calling
[MAXTEL
] = ""; // calling number
1297 if (!config
->cluster_iam_master
)
1299 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1303 if ((*buf
& 0xCA) != 0xC8)
1305 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad control header %02X\n", *buf
);
1306 STAT(tunnel_rx_errors
);
1309 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1310 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1311 // if no tunnel specified, assign one
1317 // Is this a duplicate of the first packet? (SCCRQ)
1319 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1321 if (tunnel
[i
].state
!= TUNNELOPENING
||
1322 tunnel
[i
].ip
!= ntohl(*(ipt
*) & addr
->sin_addr
) ||
1323 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1332 if (!(t
= new_tunnel()))
1334 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "No more tunnels\n");
1335 STAT(tunnel_overflow
);
1339 tunnel
[t
].ip
= ntohl(*(ipt
*) & addr
->sin_addr
);
1340 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1341 tunnel
[t
].window
= 4; // default window
1342 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, t
, " New tunnel from %u.%u.%u.%u/%u ID %d\n", tunnel
[t
].ip
>> 24, tunnel
[t
].ip
>> 16 & 255, tunnel
[t
].ip
>> 8 & 255, tunnel
[t
].ip
& 255, tunnel
[t
].port
, t
);
1343 STAT(tunnel_created
);
1346 // This is used to time out old tunnels
1347 tunnel
[t
].lastrec
= time_now
;
1349 // check sequence of this message
1351 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1352 // some to clear maybe?
1353 while (tunnel
[t
].controlc
&& (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1355 controlt
*c
= tunnel
[t
].controls
;
1356 tunnel
[t
].controls
= c
->next
;
1357 tunnel
[t
].controlc
--;
1358 c
->next
= controlfree
;
1361 tunnel
[t
].try = 0; // we have progress
1364 // If the 'ns' just received is not the 'nr' we're
1365 // expecting, just send an ack and drop it.
1367 // if 'ns' is less, then we got a retransmitted packet.
1368 // if 'ns' is greater than missed a packet. Either way
1369 // we should ignore it.
1370 if (ns
!= tunnel
[t
].nr
)
1372 // is this the sequence we were expecting?
1373 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n", t
, ns
, tunnel
[t
].nr
);
1374 STAT(tunnel_rx_errors
);
1376 if (l
) // Is this not a ZLB?
1380 // receiver advance (do here so quoted correctly in any sends below)
1381 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1382 if (skip
< 0) skip
= 0;
1383 if (skip
< tunnel
[t
].controlc
)
1385 // some control packets can now be sent that were previous stuck out of window
1386 int tosend
= tunnel
[t
].window
- skip
;
1387 controlt
*c
= tunnel
[t
].controls
;
1395 tunnel
[t
].try = 0; // first send
1396 tunnelsend(c
->buf
, c
->length
, t
);
1401 if (!tunnel
[t
].controlc
)
1402 tunnel
[t
].retry
= 0; // caught up
1405 { // if not a null message
1407 while (l
&& !(fatal
& 0x80))
1409 u16 n
= (ntohs(*(u16
*) p
) & 0x3FF);
1416 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Invalid length in AVP\n");
1417 STAT(tunnel_rx_errors
);
1424 // handle hidden AVPs
1425 if (!*config
->l2tpsecret
)
1427 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1431 if (!session
[s
].random_vector_length
)
1433 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no random vector.\n");
1437 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP\n");
1439 n
= unhide_avp(b
, t
, s
, n
);
1448 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1455 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown AVP vendor %d\n", ntohs(*(u16
*) (b
)));
1460 mtype
= ntohs(*(u16
*) (b
));
1464 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1467 case 0: // message type
1468 message
= ntohs(*(u16
*) b
);
1469 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Message type = %d (%s)\n", *b
,
1470 l2tp_message_types
[message
]);
1471 mandatorymessage
= flags
;
1473 case 1: // result code
1475 u16 rescode
= ntohs(*(u16
*)(b
));
1476 const char* resdesc
= "(unknown)";
1479 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1480 resdesc
= stopccn_result_codes
[rescode
];
1482 else if (message
== 14)
1484 if (rescode
<= MAX_CDN_RESULT_CODE
)
1485 resdesc
= cdn_result_codes
[rescode
];
1488 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Result Code %d: %s\n",
1492 u16 errcode
= ntohs(*(u16
*)(b
+ 2));
1493 const char* errdesc
= "(unknown)";
1494 if (errcode
<= MAX_ERROR_CODE
)
1495 errdesc
= error_codes
[errcode
];
1496 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error Code %d: %s\n",
1500 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error String: %.*s\n",
1506 case 2: // protocol version
1508 version
= ntohs(*(u16
*) (b
));
1509 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Protocol version = %d\n", version
);
1510 if (version
&& version
!= 0x0100)
1511 { // allow 0.0 and 1.0
1512 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Bad protocol version %04X\n",
1519 case 3: // framing capabilities
1520 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Framing capabilities\n");
1522 case 4: // bearer capabilities
1523 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Bearer capabilities\n");
1525 case 5: // tie breaker
1526 // We never open tunnels, so we don't care about tie breakers
1527 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Tie breaker\n");
1529 case 6: // firmware revision
1530 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Firmware revision\n");
1532 case 7: // host name
1533 memset(tunnel
[t
].hostname
, 0, 128);
1534 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1535 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1536 // TBA - to send to RADIUS
1538 case 8: // vendor name
1539 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1540 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1541 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1543 case 9: // assigned tunnel
1544 tunnel
[t
].far
= ntohs(*(u16
*) (b
));
1545 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1547 case 10: // rx window
1548 tunnel
[t
].window
= ntohs(*(u16
*) (b
));
1549 if (!tunnel
[t
].window
)
1550 tunnel
[t
].window
= 1; // window of 0 is silly
1551 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1553 case 11: // Challenge
1555 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " LAC requested CHAP authentication for tunnel\n");
1556 build_chap_response(b
, 2, n
, &chapresponse
);
1559 case 13: // Response
1560 // Why did they send a response? We never challenge.
1561 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " received unexpected challenge response\n");
1564 case 14: // assigned session
1565 asession
= session
[s
].far
= ntohs(*(u16
*) (b
));
1566 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " assigned session = %d\n", asession
);
1568 case 15: // call serial number
1569 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " call serial number = %d\n", ntohl(*(u32
*)b
));
1571 case 18: // bearer type
1572 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " bearer type = %d\n", ntohl(*(u32
*)b
));
1575 case 19: // framing type
1576 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " framing type = %d\n", ntohl(*(u32
*)b
));
1579 case 21: // called number
1580 memset(called
, 0, MAXTEL
);
1581 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1582 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Called <%s>\n", called
);
1584 case 22: // calling number
1585 memset(calling
, 0, MAXTEL
);
1586 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1587 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Calling <%s>\n", calling
);
1591 case 24: // tx connect speed
1594 session
[s
].tx_connect_speed
= ntohl(*(u32
*)b
);
1598 // AS5300s send connect speed as a string
1600 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1601 session
[s
].tx_connect_speed
= atol(tmp
);
1603 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " TX connect speed <%u>\n",
1604 session
[s
].tx_connect_speed
);
1606 case 38: // rx connect speed
1609 session
[s
].rx_connect_speed
= ntohl(*(u32
*)b
);
1613 // AS5300s send connect speed as a string
1615 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1616 session
[s
].rx_connect_speed
= atol(tmp
);
1618 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " RX connect speed <%u>\n",
1619 session
[s
].rx_connect_speed
);
1621 case 25: // Physical Channel ID
1623 u32 tmp
= ntohl(*(u32
*)b
);
1624 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Physical Channel ID <%X>\n", tmp
);
1627 case 29: // Proxy Authentication Type
1629 u16 authtype
= ntohs(*(u16
*)b
);
1630 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Type %d (%s)\n",
1631 authtype
, authtypes
[authtype
]);
1632 requestchap
= (authtype
== 2);
1635 case 30: // Proxy Authentication Name
1637 char authname
[64] = {0};
1638 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1639 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Name (%s)\n",
1643 case 31: // Proxy Authentication Challenge
1645 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1646 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Challenge\n");
1649 case 32: // Proxy Authentication ID
1651 u16 authid
= ntohs(*(u16
*)(b
));
1652 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth ID (%d)\n",
1654 if (session
[s
].radius
)
1655 radius
[session
[s
].radius
].id
= authid
;
1658 case 33: // Proxy Authentication Response
1660 char authresp
[64] = {0};
1661 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1662 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Response\n");
1665 case 27: // last send lcp
1666 { // find magic number
1667 u8
*p
= b
, *e
= p
+ n
;
1668 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1670 if (*p
== 5 && p
[1] == 6) // Magic-Number
1671 amagic
= ntohl(*(u32
*) (p
+ 2));
1672 else if (*p
== 3 && p
[1] == 5 && *(u16
*) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1674 else if (*p
== 7) // Protocol-Field-Compression
1675 aflags
|= SESSIONPFC
;
1676 else if (*p
== 8) // Address-and-Control-Field-Compression
1677 aflags
|= SESSIONACFC
;
1682 case 28: // last recv lcp confreq
1684 case 26: // Initial Received LCP CONFREQ
1686 case 39: // seq required - we control it as an LNS anyway...
1688 case 36: // Random Vector
1689 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1690 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1691 memcpy(session
[s
].random_vector
, b
, n
);
1692 session
[s
].random_vector_length
= n
;
1695 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Unknown AVP type %d\n", mtype
);
1702 tunnelshutdown(t
, "Unknown Mandatory AVP");
1706 case 1: // SCCRQ - Start Control Connection Request
1708 controlt
*c
= controlnew(2); // sending SCCRP
1709 control16(c
, 2, version
, 1); // protocol version
1710 control32(c
, 3, 3, 1); // framing
1711 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1712 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1713 control16(c
, 9, t
, 1); // assigned tunnel
1714 controladd(c
, t
, s
); // send the resply
1716 tunnel
[t
].state
= TUNNELOPENING
;
1719 tunnel
[t
].state
= TUNNELOPEN
;
1722 tunnel
[t
].state
= TUNNELOPEN
;
1723 controlnull(t
); // ack
1726 controlnull(t
); // ack
1727 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1728 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1731 controlnull(t
); // simply ACK
1745 STAT(session_overflow
);
1746 tunnelshutdown(t
, "No free sessions");
1754 sessionfree
= session
[s
].next
;
1755 memset(&session
[s
], 0, sizeof(session
[s
]));
1757 if (s
> config
->cluster_highest_sessionid
)
1758 config
->cluster_highest_sessionid
= s
;
1760 // make a RADIUS session
1761 if (!(r
= radiusnew(s
)))
1763 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "No free RADIUS sessions for ICRQ\n");
1764 sessionkill(s
, "no free RADIUS sesions");
1768 c
= controlnew(11); // sending ICRP
1769 session
[s
].id
= sessionid
++;
1770 session
[s
].opened
= time(NULL
);
1771 session
[s
].tunnel
= t
;
1772 session
[s
].far
= asession
;
1773 session
[s
].last_packet
= time_now
;
1774 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1775 control16(c
, 14, s
, 1); // assigned session
1776 controladd(c
, t
, s
); // send the reply
1778 // Generate a random challenge
1780 for (n
= 0; n
< 15; n
++)
1781 radius
[r
].auth
[n
] = rand();
1783 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1784 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1785 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1786 STAT(session_created
);
1793 if (amagic
== 0) amagic
= time_now
;
1794 session
[s
].magic
= amagic
; // set magic number
1795 session
[s
].l2tp_flags
= aflags
; // set flags received
1796 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1797 controlnull(t
); // ack
1798 // In CHAP state, request PAP instead
1803 controlnull(t
); // ack
1804 sessionshutdown(s
, "Closed (Received CDN)");
1807 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Missing message type\n");
1810 STAT(tunnel_rx_errors
);
1811 if (mandatorymessage
& 0x80)
1812 tunnelshutdown(t
, "Unknown message");
1814 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown message type %d\n", message
);
1817 if (chapresponse
) free(chapresponse
);
1818 cluster_send_tunnel(t
);
1822 LOG(4, 0, s
, t
, " Got a ZLB ack\n");
1829 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
1830 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1831 { // HDLC address header, discard
1837 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Short ppp length %d\n", l
);
1838 STAT(tunnel_rx_errors
);
1848 prot
= ntohs(*(u16
*) p
);
1853 if (s
&& !session
[s
].tunnel
) // Is something wrong??
1855 if (!config
->cluster_iam_master
)
1857 // Pass it off to the master to deal with..
1858 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1863 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "UDP packet contains session %d "
1864 "but no session[%d].tunnel exists (LAC said"
1865 " tunnel = %d). Dropping packet.\n", s
, s
, t
);
1866 STAT(tunnel_rx_errors
);
1872 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1873 // I'm pretty sure this isn't right -- mo.
1874 // return; // closing session, PPP not processed
1878 session
[s
].last_packet
= time_now
;
1879 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1880 processpap(t
, s
, p
, l
);
1882 else if (prot
== PPPCHAP
)
1884 session
[s
].last_packet
= time_now
;
1885 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1886 processchap(t
, s
, p
, l
);
1888 else if (prot
== PPPLCP
)
1890 session
[s
].last_packet
= time_now
;
1891 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1892 processlcp(t
, s
, p
, l
);
1894 else if (prot
== PPPIPCP
)
1896 session
[s
].last_packet
= time_now
;
1897 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1898 processipcp(t
, s
, p
, l
);
1900 else if (prot
== PPPCCP
)
1902 session
[s
].last_packet
= time_now
;
1903 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1904 processccp(t
, s
, p
, l
);
1906 else if (prot
== PPPIP
)
1908 session
[s
].last_packet
= time_now
;
1909 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
1911 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1914 processipin(t
, s
, p
, l
);
1918 STAT(tunnel_rx_errors
);
1919 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown PPP protocol %04X\n", prot
);
1924 // read and process packet on tun
1925 static void processtun(u8
* buf
, int len
)
1927 LOG_HEX(5, "Receive TUN Data", buf
, len
);
1928 STAT(tun_rx_packets
);
1929 INC_STAT(tun_rx_bytes
, len
);
1931 CSTAT(call_processtun
);
1937 LOG(1, 0, 0, 0, "Short tun packet %d bytes\n", len
);
1938 STAT(tun_rx_errors
);
1942 if (*(u16
*) (buf
+ 2) == htons(PKTIP
)) // IP
1943 processipout(buf
, len
);
1948 // Maximum number of actions to complete.
1949 // This is to avoid sending out too many packets
1951 #define MAX_ACTIONS 500
1953 static int regular_cleanups(void)
1955 static sessionidt s
= 0; // Next session to check for actions on.
1959 static clockt next_acct
= 0;
1962 LOG(3, 0, 0, 0, "Begin regular cleanup\n");
1964 for (r
= 1; r
< MAXRADIUS
; r
++)
1966 if (!radius
[r
].state
)
1968 if (radius
[r
].retry
)
1970 if (radius
[r
].retry
<= TIME
)
1973 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
1975 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
1977 // check for expired tunnels
1978 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
1980 STAT(tunnel_timeout
);
1981 tunnelkill(t
, "Expired");
1984 // check for message resend
1985 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
1987 // resend pending messages as timeout on reply
1988 if (tunnel
[t
].retry
<= TIME
)
1990 controlt
*c
= tunnel
[t
].controls
;
1991 u8 w
= tunnel
[t
].window
;
1992 tunnel
[t
].try++; // another try
1993 if (tunnel
[t
].try > 5)
1994 tunnelkill(t
, "Timeout on control message"); // game over
1998 tunnelsend(c
->buf
, c
->length
, t
);
2004 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2006 controlt
*c
= controlnew(6); // sending HELLO
2007 controladd(c
, t
, 0); // send the message
2008 LOG(3, tunnel
[t
].ip
, 0, t
, "Sending HELLO message\n");
2011 // Check for tunnel changes requested from the CLI
2012 if ((a
= cli_tunnel_actions
[t
].action
))
2014 cli_tunnel_actions
[t
].action
= 0;
2015 if (a
& CLI_TUN_KILL
)
2017 LOG(2, tunnel
[t
].ip
, 0, t
, "Dropping tunnel by CLI\n");
2018 tunnelshutdown(t
, "Requested by administrator");
2025 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2028 if (s
> config
->cluster_highest_sessionid
)
2031 if (!session
[s
].tunnel
) // Session isn't in use
2034 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2036 // IPCP has not completed yet. Resend
2037 LOG(3, session
[s
].ip
, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2038 sendipcp(session
[s
].tunnel
, s
);
2041 // check for expired sessions
2042 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2044 sessionkill(s
, "Expired");
2045 if (++count
>= MAX_ACTIONS
) break;
2049 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2050 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2052 sessionkill(s
, "No response to LCP ECHO requests");
2053 STAT(session_timeout
);
2054 if (++count
>= MAX_ACTIONS
) break;
2058 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2059 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2061 u8 b
[MAXCONTROL
] = {0};
2063 u8
*q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2067 *(u8
*)(q
+ 1) = (time_now
% 255); // ID
2068 *(u16
*)(q
+ 2) = htons(8); // Length
2069 *(u32
*)(q
+ 4) = 0; // Magic Number (not supported)
2071 LOG(4, session
[s
].ip
, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2072 (int)(time_now
- session
[s
].last_packet
));
2073 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2074 if (++count
>= MAX_ACTIONS
) break;
2077 // Check for actions requested from the CLI
2078 if ((a
= cli_session_actions
[s
].action
))
2082 cli_session_actions
[s
].action
= 0;
2083 if (a
& CLI_SESS_KILL
)
2085 LOG(2, 0, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2086 sessionshutdown(s
, "Requested by administrator");
2087 a
= 0; // dead, no need to check for other actions
2090 if (a
& CLI_SESS_NOSNOOP
)
2092 LOG(2, 0, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2093 session
[s
].snoop_ip
= 0;
2094 session
[s
].snoop_port
= 0;
2097 else if (a
& CLI_SESS_SNOOP
)
2099 LOG(2, 0, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2100 inet_toa(cli_session_actions
[s
].snoop_ip
), cli_session_actions
[s
].snoop_port
);
2102 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2103 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2107 if (a
& CLI_SESS_NOTHROTTLE
)
2109 LOG(2, 0, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2110 throttle_session(s
, 0, 0);
2113 else if (a
& CLI_SESS_THROTTLE
)
2115 LOG(2, 0, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2116 cli_session_actions
[s
].throttle_in
,
2117 cli_session_actions
[s
].throttle_out
);
2119 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2124 cluster_send_session(s
);
2126 if (++count
>= MAX_ACTIONS
) break;
2130 if (*config
->accounting_dir
&& next_acct
<= TIME
)
2132 // Dump accounting data
2133 next_acct
= TIME
+ ACCT_TIME
;
2137 if (count
>= MAX_ACTIONS
)
2138 return 1; // Didn't finish!
2140 LOG(3, 0, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count
, config
->cleanup_interval
);
2146 // Are we in the middle of a tunnel update, or radius
2149 static int still_busy(void)
2152 static clockt last_talked
= 0;
2153 static clockt start_busy_wait
= 0;
2154 if (start_busy_wait
== 0)
2155 start_busy_wait
= TIME
;
2157 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2159 if (!tunnel
[i
].controlc
)
2162 if (last_talked
!= TIME
)
2164 LOG(2,0,0,0, "Tunnel %d still has un-acked control messages.\n", i
);
2170 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2171 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2173 LOG(1, 0, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2177 for (i
= 1; i
< MAXRADIUS
; i
++)
2179 if (radius
[i
].state
== RADIUSNULL
)
2181 if (radius
[i
].state
== RADIUSWAIT
)
2184 if (last_talked
!= TIME
)
2186 LOG(2,0,0,0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2195 static fd_set readset
;
2196 static int readset_n
= 0;
2198 // main loop - gets packets on tun or udp and processes them
2199 static void mainloop(void)
2204 clockt next_cluster_ping
= 0; // send initial ping immediately
2205 time_t next_clean
= time_now
+ config
->cleanup_interval
;
2207 LOG(4, 0, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2208 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2211 FD_SET(udpfd
, &readset
);
2212 FD_SET(tunfd
, &readset
);
2213 FD_SET(controlfd
, &readset
);
2214 FD_SET(clifd
, &readset
);
2215 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2217 if (tunfd
> readset_n
) readset_n
= tunfd
;
2218 if (controlfd
> readset_n
) readset_n
= controlfd
;
2219 if (clifd
> readset_n
) readset_n
= clifd
;
2220 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2222 while (!main_quit
|| still_busy())
2228 int bgp_set
[BGP_NUM_PEERS
];
2231 if (config
->reload_config
)
2233 // Update the config state based on config settings
2237 memcpy(&r
, &readset
, sizeof(fd_set
));
2239 to
.tv_usec
= 100000; // 1/10th of a second.
2243 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2245 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2248 FD_SET(bgp_peers
[i
].sock
, &r
);
2249 if (bgp_peers
[i
].sock
> n
)
2250 n
= bgp_peers
[i
].sock
;
2255 FD_SET(bgp_peers
[i
].sock
, &w
);
2256 if (bgp_peers
[i
].sock
> n
)
2257 n
= bgp_peers
[i
].sock
;
2261 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2263 n
= select(n
+ 1, &r
, 0, 0, &to
);
2269 if (errno
== EINTR
||
2270 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2273 LOG(0, 0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2279 struct sockaddr_in addr
;
2280 int alen
= sizeof(addr
);
2281 if (FD_ISSET(udpfd
, &r
))
2284 for (c
= 0; c
< config
->multi_read_count
; c
++)
2286 if ((n
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
2287 processudp(buf
, n
, &addr
);
2292 if (FD_ISSET(tunfd
, &r
))
2295 for (c
= 0; c
< config
->multi_read_count
; c
++)
2297 if ((n
= read(tunfd
, buf
, sizeof(buf
))) > 0)
2304 if (config
->cluster_iam_master
)
2305 for (i
= 0; i
< config
->num_radfds
; i
++)
2306 if (FD_ISSET(radfds
[i
], &r
))
2307 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2309 if (FD_ISSET(cluster_sockfd
, &r
))
2312 size
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
);
2313 processcluster(buf
, size
, addr
.sin_addr
.s_addr
);
2316 if (FD_ISSET(controlfd
, &r
))
2317 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
, alen
);
2319 if (FD_ISSET(clifd
, &r
))
2321 struct sockaddr_in addr
;
2323 int len
= sizeof(addr
);
2325 if ((sockfd
= accept(clifd
, (struct sockaddr
*)&addr
, &len
)) <= 0)
2327 LOG(0, 0, 0, 0, "accept error: %s\n", strerror(errno
));
2338 // Runs on every machine (master and slaves).
2339 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
2341 // Check to see which of the cluster is still alive..
2343 cluster_send_ping(basetime
); // Only does anything if we're a slave
2344 cluster_check_master(); // ditto.
2346 cluster_heartbeat(); // Only does anything if we're a master.
2347 cluster_check_slaves(); // ditto.
2349 master_update_counts(); // If we're a slave, send our byte counters to our master.
2351 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
2352 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
2354 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
2357 // Run token bucket filtering queue..
2358 // Only run it every 1/10th of a second.
2359 // Runs on all machines both master and slave.
2361 static clockt last_run
= 0;
2362 if (last_run
!= TIME
)
2369 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2370 * something to read, else under load this will never actually run....
2373 if (config
->cluster_iam_master
&& next_clean
<= time_now
)
2375 if (regular_cleanups())
2378 next_clean
= time_now
+ 1 ; // Didn't finish. Check quickly.
2382 next_clean
= time_now
+ config
->cleanup_interval
; // Did. Move to next interval.
2387 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2389 bgp_process(&bgp_peers
[i
],
2390 bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0,
2391 bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0);
2396 // Are we the master and shutting down??
2397 if (config
->cluster_iam_master
)
2398 cluster_heartbeat(); // Flush any queued changes..
2400 // Ok. Notify everyone we're shutting down. If we're
2401 // the master, this will force an election.
2402 cluster_send_ping(0);
2405 // Important!!! We MUST not process any packets past this point!
2408 static void stripdomain(char *host
)
2412 if ((p
= strchr(host
, '.')))
2418 FILE *resolv
= fopen("/etc/resolv.conf", "r");
2424 while (fgets(buf
, sizeof(buf
), resolv
))
2426 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
2429 if (!isspace(buf
[6]))
2433 while (isspace(*b
)) b
++;
2438 while (*b
&& !isspace(*b
)) b
++;
2440 if (buf
[0] == 'd') // domain is canonical
2446 // first search line
2449 // hold, may be subsequent domain line
2450 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
2461 int hl
= strlen(host
);
2462 int dl
= strlen(domain
);
2463 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
2464 host
[hl
-dl
- 1] = 0;
2468 *p
= 0; // everything after first dot
2473 // Init data structures
2474 static void initdata(int optdebug
, char *optconfig
)
2478 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
2480 LOG(0, 0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
2483 if (!(config
= shared_malloc(sizeof(struct configt
))))
2485 LOG(0, 0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2488 memset(config
, 0, sizeof(struct configt
));
2489 time(&config
->start_time
);
2490 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
2491 config
->debug
= optdebug
;
2492 config
->num_tbfs
= MAXTBFS
;
2493 config
->rl_rate
= 28; // 28kbps
2495 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
2497 LOG(0, 0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
2500 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
2502 LOG(0, 0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
2506 if (!(sess_count
= shared_malloc(sizeof(sessioncountt
) * MAXSESSION
)))
2508 LOG(0, 0, 0, 0, "Error doing malloc for sessions_count: %s\n", strerror(errno
));
2512 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
2514 LOG(0, 0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
2518 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
2520 LOG(0, 0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
2525 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2527 LOG(0, 0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2530 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2533 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2535 LOG(0, 0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2538 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2540 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2542 LOG(0, 0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2545 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2547 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2548 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2549 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2550 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2552 // Put all the sessions on the free list marked as undefined.
2553 for (i
= 1; i
< MAXSESSION
- 1; i
++)
2555 session
[i
].next
= i
+ 1;
2556 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2558 session
[MAXSESSION
- 1].next
= 0;
2561 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2562 for (i
= 1; i
< MAXTUNNEL
- 1; i
++)
2563 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2567 // Grab my hostname unless it's been specified
2568 gethostname(hostname
, sizeof(hostname
));
2569 stripdomain(hostname
);
2572 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2575 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2577 LOG(0, 0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2583 static int assign_ip_address(sessionidt s
)
2587 time_t best_time
= time_now
;
2588 char *u
= session
[s
].user
;
2592 CSTAT(call_assign_ip_address
);
2594 for (i
= 1; i
< ip_pool_size
; i
++)
2596 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2599 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2606 if (ip_address_pool
[i
].last
< best_time
)
2609 if (!(best_time
= ip_address_pool
[i
].last
))
2610 break; // never used, grab this one
2616 LOG(0, 0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2620 session
[s
].ip
= ip_address_pool
[best
].address
;
2621 session
[s
].ip_pool_index
= best
;
2622 ip_address_pool
[best
].assigned
= 1;
2623 ip_address_pool
[best
].last
= time_now
;
2624 ip_address_pool
[best
].session
= s
;
2625 if (session
[s
].walled_garden
)
2626 /* Don't track addresses of users in walled garden (note: this
2627 means that their address isn't "sticky" even if they get
2629 ip_address_pool
[best
].user
[0] = 0;
2631 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2634 LOG(4, ip_address_pool
[best
].address
, s
, session
[s
].tunnel
,
2635 "assign_ip_address(): %s ip address %d from pool\n", reuse
? "Reusing" : "Allocating", best
);
2640 static void free_ip_address(sessionidt s
)
2642 int i
= session
[s
].ip_pool_index
;
2645 CSTAT(call_free_ip_address
);
2648 return; // what the?
2650 if (i
< 0) // Is this actually part of the ip pool?
2654 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2656 ip_address_pool
[i
].assigned
= 0;
2657 ip_address_pool
[i
].session
= 0;
2658 ip_address_pool
[i
].last
= time_now
;
2662 // Fsck the address pool against the session table.
2663 // Normally only called when we become a master.
2665 // This isn't perfect: We aren't keep tracking of which
2666 // users used to have an IP address.
2668 void rebuild_address_pool(void)
2673 // Zero the IP pool allocation, and build
2674 // a map from IP address to pool index.
2675 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2677 ip_address_pool
[i
].assigned
= 0;
2678 ip_address_pool
[i
].session
= 0;
2679 if (!ip_address_pool
[i
].address
)
2682 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2685 for (i
= 0; i
< MAXSESSION
; ++i
)
2688 if (!session
[i
].ip
|| !session
[i
].tunnel
)
2690 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2692 if (session
[i
].ip_pool_index
< 0)
2694 // Not allocated out of the pool.
2695 if (ipid
< 1) // Not found in the pool either? good.
2698 LOG(0, 0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2699 i
, inet_toa(session
[i
].ip
), ipid
);
2701 // Fall through and process it as part of the pool.
2705 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2707 LOG(0, 0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2709 session
[i
].ip_pool_index
= ipid
;
2713 ip_address_pool
[ipid
].assigned
= 1;
2714 ip_address_pool
[ipid
].session
= i
;
2715 ip_address_pool
[ipid
].last
= time_now
;
2716 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2717 session
[i
].ip_pool_index
= ipid
;
2718 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
2723 // Fix the address pool to match a changed session.
2724 // (usually when the master sends us an update).
2725 static void fix_address_pool(int sid
)
2729 ipid
= session
[sid
].ip_pool_index
;
2731 if (ipid
> ip_pool_size
)
2732 return; // Ignore it. rebuild_address_pool will fix it up.
2734 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
2735 return; // Just ignore it. rebuild_address_pool will take care of it.
2737 ip_address_pool
[ipid
].assigned
= 1;
2738 ip_address_pool
[ipid
].session
= sid
;
2739 ip_address_pool
[ipid
].last
= time_now
;
2740 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2744 // Add a block of addresses to the IP pool to hand out.
2746 static void add_to_ip_pool(u32 addr
, u32 mask
)
2750 mask
= 0xffffffff; // Host route only.
2754 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
2757 for (i
= addr
;(i
& mask
) == addr
; ++i
)
2759 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
2760 continue; // Skip 0 and broadcast addresses.
2762 ip_address_pool
[ip_pool_size
].address
= i
;
2763 ip_address_pool
[ip_pool_size
].assigned
= 0;
2765 if (ip_pool_size
>= MAXIPPOOL
)
2767 LOG(0,0,0,0, "Overflowed IP pool adding %s\n", inet_toa(htonl(addr
)) );
2773 // Initialize the IP address pool
2774 static void initippool()
2779 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2781 if (!(f
= fopen(IPPOOLFILE
, "r")))
2783 LOG(0, 0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2787 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2790 buf
[4095] = 0; // Force it to be zero terminated/
2792 if (*buf
== '#' || *buf
== '\n')
2793 continue; // Skip comments / blank lines
2794 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2795 if ((p
= (char *)strchr(buf
, ':')))
2799 src
= inet_addr(buf
);
2800 if (src
== INADDR_NONE
)
2802 LOG(0, 0, 0, 0, "Invalid address pool IP %s\n", buf
);
2805 // This entry is for a specific IP only
2806 if (src
!= config
->bind_address
)
2811 if ((p
= (char *)strchr(pool
, '/')))
2815 u32 start
= 0, mask
= 0;
2817 LOG(2, 0, 0, 0, "Adding IP address range %s\n", buf
);
2819 if (!*p
|| !(numbits
= atoi(p
)))
2821 LOG(0, 0, 0, 0, "Invalid pool range %s\n", buf
);
2824 start
= ntohl(inet_addr(pool
));
2825 mask
= (u32
)(pow(2, numbits
) - 1) << (32 - numbits
);
2827 // Add a static route for this pool
2828 LOG(5, 0, 0, 0, "Adding route for address pool %s/%u\n", inet_toa(htonl(start
)), 32 + mask
);
2829 routeset(0, start
, mask
, 0, 1);
2831 add_to_ip_pool(start
, mask
);
2835 // It's a single ip address
2836 add_to_ip_pool(inet_addr(pool
), 0);
2840 LOG(1, 0, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
2843 void snoop_send_packet(char *packet
, u16 size
, ipt destination
, u16 port
)
2845 struct sockaddr_in snoop_addr
= {0};
2846 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2849 snoop_addr
.sin_family
= AF_INET
;
2850 snoop_addr
.sin_addr
.s_addr
= destination
;
2851 snoop_addr
.sin_port
= ntohs(port
);
2853 LOG(5, 0, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n",
2854 packet
, size
, inet_toa(snoop_addr
.sin_addr
.s_addr
), htons(snoop_addr
.sin_port
));
2855 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
2856 LOG(0, 0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
2857 STAT(packets_snooped
);
2860 static void dump_acct_info()
2862 char filename
[1024];
2864 time_t t
= time(NULL
);
2869 CSTAT(call_dump_acct_info
);
2871 strftime(timestr
, 64, "%Y%m%d%H%M%S", localtime(&t
));
2872 snprintf(filename
, 1024, "%s/%s", config
->accounting_dir
, timestr
);
2874 for (i
= 0; i
< MAXSESSION
; i
++)
2876 if (!session
[i
].opened
|| !session
[i
].ip
|| !(session
[i
].cin
|| session
[i
].cout
) || !*session
[i
].user
|| session
[i
].walled_garden
)
2880 time_t now
= time(NULL
);
2881 if (!(f
= fopen(filename
, "w")))
2883 LOG(0, 0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
2886 LOG(3, 0, 0, 0, "Dumping accounting information to %s\n", filename
);
2887 fprintf(f
, "# dslwatch.pl dump file V1.01\n"
2891 "# format: username ip qos uptxoctets downrxoctets\n",
2897 LOG(4, 0, 0, 0, "Dumping accounting information for %s\n", session
[i
].user
);
2898 fprintf(f
, "%s %s %d %u %u\n",
2899 session
[i
].user
, // username
2900 inet_toa(htonl(session
[i
].ip
)), // ip
2901 (session
[i
].throttle_in
|| session
[i
].throttle_out
) ? 2 : 1, // qos
2902 (u32
)session
[i
].cin
, // uptxoctets
2903 (u32
)session
[i
].cout
); // downrxoctets
2905 session
[i
].pin
= session
[i
].cin
= 0;
2906 session
[i
].pout
= session
[i
].cout
= 0;
2914 int main(int argc
, char *argv
[])
2918 char *optconfig
= CONFIGFILE
;
2920 time(&basetime
); // start clock
2923 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
2928 if (fork()) exit(0);
2930 freopen("/dev/null", "r", stdin
);
2931 freopen("/dev/null", "w", stdout
);
2932 freopen("/dev/null", "w", stderr
);
2941 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
2944 printf("Args are:\n"
2945 "\t-d\t\tDetach from terminal\n"
2946 "\t-c <file>\tConfig file\n"
2947 "\t-h <hostname>\tForce hostname\n"
2955 // Start the timer routine off
2957 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
2958 signal(SIGALRM
, sigalrm_handler
);
2959 siginterrupt(SIGALRM
, 0);
2962 initdata(optdebug
, optconfig
);
2966 init_tbf(config
->num_tbfs
);
2968 LOG(0, 0, 0, 0, "L2TPNS version " VERSION
"\n");
2969 LOG(0, 0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
2970 LOG(0, 0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
2973 rlim
.rlim_cur
= RLIM_INFINITY
;
2974 rlim
.rlim_max
= RLIM_INFINITY
;
2975 // Remove the maximum core size
2976 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
2977 LOG(0, 0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
2978 // Make core dumps go to /tmp
2982 if (config
->scheduler_fifo
)
2985 struct sched_param params
= {0};
2986 params
.sched_priority
= 1;
2988 if (get_nprocs() < 2)
2990 LOG(0, 0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
2991 config
->scheduler_fifo
= 0;
2995 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
2997 LOG(1, 0, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3001 LOG(0, 0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3002 config
->scheduler_fifo
= 0;
3007 /* Set up the cluster communications port. */
3008 if (cluster_init() < 0)
3012 signal(SIGPIPE
, SIG_IGN
);
3013 bgp_setup(config
->as_number
);
3014 bgp_add_route(config
->bind_address
, 0xffffffff);
3015 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3017 if (config
->neighbour
[i
].name
[0])
3018 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3019 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3020 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3025 LOG(1, 0, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3033 signal(SIGHUP
, sighup_handler
);
3034 signal(SIGTERM
, sigterm_handler
);
3035 signal(SIGINT
, sigterm_handler
);
3036 signal(SIGQUIT
, sigquit_handler
);
3037 signal(SIGCHLD
, sigchild_handler
);
3039 // Prevent us from getting paged out
3040 if (config
->lock_pages
)
3042 if (!mlockall(MCL_CURRENT
))
3043 LOG(1, 0, 0, 0, "Locking pages into memory\n");
3045 LOG(0, 0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3050 // Drop privileges here
3051 if (config
->target_uid
> 0 && geteuid() == 0)
3052 setuid(config
->target_uid
);
3057 /* try to shut BGP down cleanly; with luck the sockets will be
3058 writable since we're out of the select */
3059 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3060 if (bgp_peers
[i
].state
== Established
)
3061 bgp_stop(&bgp_peers
[i
]);
3064 /* remove plugins (so cleanup code gets run) */
3067 // Remove the PID file if we wrote it
3068 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3069 unlink(config
->pid_file
);
3071 /* kill CLI children */
3072 signal(SIGTERM
, SIG_IGN
);
3077 static void sighup_handler(int sig
)
3079 if (log_stream
&& log_stream
!= stderr
)
3088 static void sigalrm_handler(int sig
)
3090 // Log current traffic stats
3092 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3093 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3094 (udp_rx
/ 1024.0 / 1024.0 * 8),
3095 (eth_tx
/ 1024.0 / 1024.0 * 8),
3096 (eth_rx
/ 1024.0 / 1024.0 * 8),
3097 (udp_tx
/ 1024.0 / 1024.0 * 8),
3098 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3099 udp_rx_pkt
, eth_rx_pkt
);
3101 udp_tx
= udp_rx
= 0;
3102 udp_rx_pkt
= eth_rx_pkt
= 0;
3103 eth_tx
= eth_rx
= 0;
3105 if (config
->dump_speed
)
3106 printf("%s\n", config
->bandwidth
);
3108 // Update the internal time counter
3110 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3115 struct param_timer p
= { time_now
};
3116 run_plugins(PLUGIN_TIMER
, &p
);
3121 static void sigterm_handler(int sig
)
3123 LOG(1, 0, 0, 0, "Shutting down cleanly\n");
3124 if (config
->save_state
)
3130 static void sigquit_handler(int sig
)
3134 LOG(1, 0, 0, 0, "Shutting down without saving sessions\n");
3135 for (i
= 1; i
< MAXSESSION
; i
++)
3137 if (session
[i
].opened
)
3138 sessionkill(i
, "L2TPNS Closing");
3140 for (i
= 1; i
< MAXTUNNEL
; i
++)
3142 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3143 tunnelshutdown(i
, "L2TPNS Closing");
3149 static void sigchild_handler(int sig
)
3151 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3155 static void read_state()
3161 char magic
[sizeof(DUMP_MAGIC
) - 1];
3164 if (!config
->save_state
)
3170 if (stat(STATEFILE
, &sb
) < 0)
3176 if (sb
.st_mtime
< (time(NULL
) - 60))
3178 LOG(0, 0, 0, 0, "State file is too old to read, ignoring\n");
3183 f
= fopen(STATEFILE
, "r");
3188 LOG(0, 0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3192 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3194 LOG(0, 0, 0, 0, "Bad state file magic\n");
3198 LOG(1, 0, 0, 0, "Reading state information\n");
3199 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3201 LOG(0, 0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3205 if (buf
[0] > ip_pool_size
)
3207 LOG(0, 0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3211 LOG(2, 0, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3212 for (i
= 0; i
< buf
[0]; i
++)
3214 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3216 LOG(0, 0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3220 if (itmp
.address
!= ip_address_pool
[i
].address
)
3222 LOG(0, 0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3226 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3229 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3231 LOG(0, 0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3235 LOG(2, 0, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3236 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3238 LOG(0, 0, 0, 0, "Error reading tunnel data from state file\n");
3242 for (i
= 0; i
< MAXTUNNEL
; i
++)
3244 tunnel
[i
].controlc
= 0;
3245 tunnel
[i
].controls
= NULL
;
3246 tunnel
[i
].controle
= NULL
;
3247 if (*tunnel
[i
].hostname
)
3248 LOG(3, 0, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3251 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3253 LOG(0, 0, 0, 0, "Error/mismatch reading session header from state file\n");
3257 LOG(2, 0, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3258 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3260 LOG(0, 0, 0, 0, "Error reading session data from state file\n");
3264 for (i
= 0; i
< MAXSESSION
; i
++)
3266 session
[i
].tbf_in
= 0;
3267 session
[i
].tbf_out
= 0;
3268 if (session
[i
].opened
)
3270 LOG(2, 0, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3272 sessionsetup(session
[i
].tunnel
, i
);
3277 LOG(0, 0, 0, 0, "Loaded saved state information\n");
3280 static void dump_state()
3285 if (!config
->save_state
)
3290 if (!(f
= fopen(STATEFILE
, "w")))
3293 LOG(1, 0, 0, 0, "Dumping state information\n");
3295 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3298 LOG(2, 0, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3299 buf
[0] = ip_pool_size
;
3300 buf
[1] = sizeof(ippoolt
);
3301 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3303 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3306 LOG(2, 0, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3308 buf
[1] = sizeof(tunnelt
);
3309 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3311 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3314 LOG(2, 0, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3315 buf
[0] = MAXSESSION
;
3316 buf
[1] = sizeof(sessiont
);
3317 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3319 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3327 LOG(0, 0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3331 static void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
)
3334 *challenge_response
= NULL
;
3336 if (!*config
->l2tpsecret
)
3338 LOG(0, 0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3342 LOG(4, 0, 0, 0, " Building challenge response for CHAP request\n");
3344 *challenge_response
= (char *)calloc(17, 1);
3347 MD5Update(&ctx
, &id
, 1);
3348 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3349 MD5Update(&ctx
, challenge
, challenge_length
);
3350 MD5Final(*challenge_response
, &ctx
);
3355 static int facility_value(char *name
)
3358 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3360 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3361 return facilitynames
[i
].c_val
;
3366 static void update_config()
3369 static int timeout
= 0;
3370 static int interval
= 0;
3380 if (*config
->log_filename
)
3382 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3384 char *p
= config
->log_filename
+ 7;
3387 openlog("l2tpns", LOG_PID
, facility_value(p
));
3391 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3393 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3395 fseek(log_stream
, 0, SEEK_END
);
3396 setbuf(log_stream
, NULL
);
3400 log_stream
= stderr
;
3401 setbuf(log_stream
, NULL
);
3407 log_stream
= stderr
;
3408 setbuf(log_stream
, NULL
);
3413 config
->numradiusservers
= 0;
3414 for (i
= 0; i
< MAXRADSERVER
; i
++)
3415 if (config
->radiusserver
[i
])
3417 config
->numradiusservers
++;
3418 // Set radius port: if not set, take the port from the
3419 // first radius server. For the first radius server,
3420 // take the #defined default value from l2tpns.h
3422 // test twice, In case someone works with
3423 // a secondary radius server without defining
3424 // a primary one, this will work even then.
3425 if (i
>0 && !config
->radiusport
[i
])
3426 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3427 if (!config
->radiusport
[i
])
3428 config
->radiusport
[i
] = RADPORT
;
3431 if (!config
->numradiusservers
)
3433 LOG(0, 0, 0, 0, "No RADIUS servers defined!\n");
3436 config
->num_radfds
= 2 << RADIUS_SHIFT
;
3439 for (i
= 0; i
< MAXPLUGINS
; i
++)
3441 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3444 if (*config
->plugins
[i
])
3447 add_plugin(config
->plugins
[i
]);
3449 else if (*config
->old_plugins
[i
])
3452 remove_plugin(config
->old_plugins
[i
]);
3455 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3456 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
3457 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3458 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3459 if (!*config
->cluster_interface
)
3460 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3462 if (!config
->cluster_hb_interval
)
3463 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3465 if (!config
->cluster_hb_timeout
)
3466 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3468 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3470 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3471 // late, ensure we're sufficiently larger than that
3472 int t
= 4 * config
->cluster_hb_interval
+ 11;
3474 if (config
->cluster_hb_timeout
< t
)
3476 LOG(0,0,0,0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3477 config
->cluster_hb_timeout
= t
;
3480 // Push timing changes to the slaves immediately if we're the master
3481 if (config
->cluster_iam_master
)
3482 cluster_heartbeat();
3484 interval
= config
->cluster_hb_interval
;
3485 timeout
= config
->cluster_hb_timeout
;
3489 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3492 if ((f
= fopen(config
->pid_file
, "w")))
3494 fprintf(f
, "%d\n", getpid());
3496 config
->wrote_pid
= 1;
3500 LOG(0, 0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3504 config
->reload_config
= 0;
3507 static void read_config_file()
3511 if (!config
->config_file
) return;
3512 if (!(f
= fopen(config
->config_file
, "r")))
3514 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3518 LOG(3, 0, 0, 0, "Reading config file %s\n", config
->config_file
);
3520 LOG(3, 0, 0, 0, "Done reading config file\n");
3525 int sessionsetup(tunnelidt t
, sessionidt s
)
3527 // A session now exists, set it up
3533 CSTAT(call_sessionsetup
);
3535 LOG(3, session
[s
].ip
, s
, t
, "Doing session setup for session\n");
3537 if (!session
[s
].ip
|| session
[s
].ip
== 0xFFFFFFFE)
3539 assign_ip_address(s
);
3542 LOG(0, 0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3543 sessionshutdown(s
, "No IP addresses available");
3546 LOG(3, 0, s
, t
, " No IP allocated. Assigned %s from pool\n",
3547 inet_toa(htonl(session
[s
].ip
)));
3551 // Make sure this is right
3552 session
[s
].tunnel
= t
;
3554 // zap old sessions with same IP and/or username
3555 // Don't kill gardened sessions - doing so leads to a DoS
3556 // from someone who doesn't need to know the password
3559 user
= session
[s
].user
;
3560 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3562 if (i
== s
) continue;
3563 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3564 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3565 sessionkill(i
, "Duplicate session for users");
3572 // Add the route for this session.
3573 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3575 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
3576 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
3579 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
3582 // Static IPs need to be routed if not already
3583 // convered by a Framed-Route. Anything else is part
3584 // of the IP address pool and is already routed, it
3585 // just needs to be added to the IP cache.
3586 if (session
[s
].ip_pool_index
== -1) // static ip
3588 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
3591 cache_ipmap(session
[s
].ip
, s
);
3594 if (!session
[s
].unique_id
)
3596 // did this session just finish radius?
3597 LOG(3, session
[s
].ip
, s
, t
, "Sending initial IPCP to client\n");
3599 session
[s
].unique_id
= ++last_id
;
3602 // Run the plugin's against this new session.
3604 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3605 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3608 // Allocate TBFs if throttled
3609 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3610 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3612 session
[s
].last_packet
= time_now
;
3615 char *sessionip
, *tunnelip
;
3616 sessionip
= strdup(inet_toa(htonl(session
[s
].ip
)));
3617 tunnelip
= strdup(inet_toa(htonl(tunnel
[t
].ip
)));
3618 LOG(2, session
[s
].ip
, s
, t
, "Login by %s at %s from %s (%s)\n",
3619 session
[s
].user
, sessionip
, tunnelip
, tunnel
[t
].hostname
);
3620 if (sessionip
) free(sessionip
);
3621 if (tunnelip
) free(tunnelip
);
3624 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3626 return 1; // RADIUS OK and IP allocated, done...
3630 // This session just got dropped on us by the master or something.
3631 // Make sure our tables up up to date...
3633 int load_session(sessionidt s
, sessiont
*new)
3639 if (new->ip_pool_index
>= MAXIPPOOL
||
3640 new->tunnel
>= MAXTUNNEL
)
3642 LOG(0,0,s
,0, "Strange session update received!\n");
3643 // FIXME! What to do here?
3648 // Ok. All sanity checks passed. Now we're committed to
3649 // loading the new session.
3652 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3654 // See if routes/ip cache need updating
3655 if (new->ip
!= session
[s
].ip
)
3658 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3659 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
3660 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
3668 // remove old routes...
3669 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3671 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
3672 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
3675 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
3681 if (session
[s
].ip_pool_index
== -1) // static IP
3683 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
3685 else // It's part of the IP pool, remove it manually.
3686 uncache_ipmap(session
[s
].ip
);
3691 // add new routes...
3692 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
3694 if ((new->ip
& new->route
[i
].mask
) ==
3695 (new->route
[i
].ip
& new->route
[i
].mask
))
3698 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
3704 // If there's a new one, add it.
3705 if (new->ip_pool_index
== -1)
3707 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
3710 cache_ipmap(new->ip
, s
);
3714 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
3715 // for walking the sessions to forward byte counts to the master.
3716 config
->cluster_highest_sessionid
= s
;
3718 // TEMP: old session struct used a u32 to define the throttle
3719 // speed for both up/down, new uses a u16 for each. Deal with
3720 // sessions from an old master for migration.
3721 if (new->throttle_out
== 0 && new->tbf_out
)
3722 new->throttle_out
= new->throttle_in
;
3724 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
3726 // Do fixups into address pool.
3727 if (new->ip_pool_index
!= -1)
3728 fix_address_pool(s
);
3733 static void initplugins()
3737 loaded_plugins
= ll_init();
3738 // Initialize the plugins to nothing
3739 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
3740 plugins
[i
] = ll_init();
3743 static void *open_plugin(char *plugin_name
, int load
)
3745 char path
[256] = "";
3747 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
3748 LOG(2, 0, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
3749 return dlopen(path
, RTLD_NOW
);
3752 // plugin callback to get a config value
3753 static void *getconfig(char *key
, enum config_typet type
)
3757 for (i
= 0; config_values
[i
].key
; i
++)
3759 if (!strcmp(config_values
[i
].key
, key
))
3761 if (config_values
[i
].type
== type
)
3762 return ((void *) config
) + config_values
[i
].offset
;
3764 LOG(1, 0, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
3765 key
, type
, config_values
[i
].type
);
3771 LOG(1, 0, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
3775 static int add_plugin(char *plugin_name
)
3777 static struct pluginfuncs funcs
= {
3782 sessiontbysessionidt
,
3783 sessionidtbysessiont
,
3789 cluster_send_session
,
3792 void *p
= open_plugin(plugin_name
, 1);
3793 int (*initfunc
)(struct pluginfuncs
*);
3798 LOG(1, 0, 0, 0, " Plugin load failed: %s\n", dlerror());
3802 if (ll_contains(loaded_plugins
, p
))
3805 return 0; // already loaded
3809 int *v
= dlsym(p
, "plugin_api_version");
3810 if (!v
|| *v
!= PLUGIN_API_VERSION
)
3812 LOG(1, 0, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
3818 if ((initfunc
= dlsym(p
, "plugin_init")))
3820 if (!initfunc(&funcs
))
3822 LOG(1, 0, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
3828 ll_push(loaded_plugins
, p
);
3830 for (i
= 0; i
< max_plugin_functions
; i
++)
3833 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3835 LOG(3, 0, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
3836 ll_push(plugins
[i
], x
);
3840 LOG(2, 0, 0, 0, " Loaded plugin %s\n", plugin_name
);
3844 static void run_plugin_done(void *plugin
)
3846 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
3852 static int remove_plugin(char *plugin_name
)
3854 void *p
= open_plugin(plugin_name
, 0);
3860 if (ll_contains(loaded_plugins
, p
))
3863 for (i
= 0; i
< max_plugin_functions
; i
++)
3866 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3867 ll_delete(plugins
[i
], x
);
3870 ll_delete(loaded_plugins
, p
);
3876 LOG(2, 0, 0, 0, "Removed plugin %s\n", plugin_name
);
3880 int run_plugins(int plugin_type
, void *data
)
3882 int (*func
)(void *data
);
3884 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
3885 return PLUGIN_RET_ERROR
;
3887 ll_reset(plugins
[plugin_type
]);
3888 while ((func
= ll_next(plugins
[plugin_type
])))
3892 if (r
!= PLUGIN_RET_OK
)
3893 return r
; // stop here
3896 return PLUGIN_RET_OK
;
3899 static void plugins_done()
3903 ll_reset(loaded_plugins
);
3904 while ((p
= ll_next(loaded_plugins
)))
3908 static void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
, int alen
)
3910 struct nsctl request
;
3911 struct nsctl response
;
3912 int type
= unpack_control(&request
, buf
, len
);
3916 if (log_stream
&& config
->debug
>= 4)
3920 LOG(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Bogus control message (%d)\n", type
);
3924 LOG(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Received ");
3925 dump_control(&request
, log_stream
);
3931 case NSCTL_REQ_LOAD
:
3932 if (request
.argc
!= 1)
3934 response
.type
= NSCTL_RES_ERR
;
3936 response
.argv
[0] = "name of plugin required";
3938 else if ((r
= add_plugin(request
.argv
[0])) < 1)
3940 response
.type
= NSCTL_RES_ERR
;
3942 response
.argv
[0] = !r
3943 ? "plugin already loaded"
3944 : "error loading plugin";
3948 response
.type
= NSCTL_RES_OK
;
3954 case NSCTL_REQ_UNLOAD
:
3955 if (request
.argc
!= 1)
3957 response
.type
= NSCTL_RES_ERR
;
3959 response
.argv
[0] = "name of plugin required";
3961 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
3963 response
.type
= NSCTL_RES_ERR
;
3965 response
.argv
[0] = !r
3966 ? "plugin not loaded"
3967 : "plugin not found";
3971 response
.type
= NSCTL_RES_OK
;
3977 case NSCTL_REQ_HELP
:
3978 response
.type
= NSCTL_RES_OK
;
3981 ll_reset(loaded_plugins
);
3982 while ((p
= ll_next(loaded_plugins
)))
3984 char **help
= dlsym(p
, "plugin_control_help");
3985 while (response
.argc
< 0xff && help
&& *help
)
3986 response
.argv
[response
.argc
++] = *help
++;
3991 case NSCTL_REQ_CONTROL
:
3993 struct param_control param
= {
3994 config
->cluster_iam_master
,
4001 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4003 if (r
== PLUGIN_RET_ERROR
)
4005 response
.type
= NSCTL_RES_ERR
;
4007 response
.argv
[0] = param
.additional
4009 : "error returned by plugin";
4011 else if (r
== PLUGIN_RET_NOTMASTER
)
4013 static char msg
[] = "must be run on master: 000.000.000.000";
4015 response
.type
= NSCTL_RES_ERR
;
4017 if (config
->cluster_master_address
)
4019 strcpy(msg
+ 23, inet_toa(config
->cluster_master_address
));
4020 response
.argv
[0] = msg
;
4024 response
.argv
[0] = "must be run on master: none elected";
4027 else if (!(param
.response
& NSCTL_RESPONSE
))
4029 response
.type
= NSCTL_RES_ERR
;
4031 response
.argv
[0] = param
.response
4032 ? "unrecognised response value from plugin"
4033 : "unhandled action";
4037 response
.type
= param
.response
;
4039 if (param
.additional
)
4042 response
.argv
[0] = param
.additional
;
4050 response
.type
= NSCTL_RES_ERR
;
4052 response
.argv
[0] = "error unpacking control packet";
4055 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4058 LOG(2, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Failed to allocate nsctl response\n");
4062 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4065 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4066 if (log_stream
&& config
->debug
>= 4)
4068 LOG(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Sent ");
4069 dump_control(&response
, log_stream
);
4073 LOG(2, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Failed to pack nsctl response (%d)\n", r
);
4078 static tunnelidt
new_tunnel()
4081 for (i
= 1; i
< MAXTUNNEL
; i
++)
4083 if (tunnel
[i
].state
== TUNNELFREE
)
4085 LOG(4, 0, 0, i
, "Assigning tunnel ID %d\n", i
);
4086 if (i
> config
->cluster_highest_tunnelid
)
4087 config
->cluster_highest_tunnelid
= i
;
4091 LOG(0, 0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4096 // We're becoming the master. Do any required setup..
4098 // This is principally telling all the plugins that we're
4099 // now a master, and telling them about all the sessions
4100 // that are active too..
4102 void become_master(void)
4105 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4107 // running a bunch of iptables commands is slow and can cause
4108 // the master to drop tunnels on takeover--kludge around the
4109 // problem by forking for the moment (note: race)
4110 if (!fork_and_close())
4112 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4114 if (!session
[s
].tunnel
) // Not an in-use session.
4117 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4123 for (i
= 0; i
< config
->num_radfds
; i
++)
4125 FD_SET(radfds
[i
], &readset
);
4126 if (radfds
[i
] > readset_n
)
4127 readset_n
= radfds
[i
];
4131 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4137 if (CLI_HELP_REQUESTED
)
4138 return CLI_HELP_NO_ARGS
;
4141 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4143 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4146 if (!session
[s
].tunnel
)
4149 idle
= time_now
- session
[s
].last_packet
;
4150 idle
/= 5 ; // In multiples of 5 seconds.
4160 for (i
= 0; i
< 63; ++i
)
4162 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4164 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4165 cli_print(cli
, "%d total sessions open.", count
);
4169 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4175 if (CLI_HELP_REQUESTED
)
4176 return CLI_HELP_NO_ARGS
;
4179 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4181 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4184 if (!session
[s
].tunnel
)
4187 d
= time_now
- session
[s
].opened
;
4190 while (d
> 1 && open
< 32)
4200 for (i
= 0; i
< 30; ++i
)
4202 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4205 cli_print(cli
, "%d total sessions open.", count
);
4211 * This unencodes the AVP using the L2TP CHAP secret and the
4212 * previously stored random vector. It replaces the hidden data with
4213 * the cleartext data and returns the length of the cleartext data
4214 * (including the AVP "header" of 6 bytes).
4216 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4218 static int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
)
4223 u8 working_vector
[16];
4224 uint16_t hidden_length
;
4229 // Find the AVP type.
4230 type
[0] = *(avp
+ 4);
4231 type
[1] = *(avp
+ 5);
4233 // Line up with the hidden data
4234 cursor
= output
= avp
+ 6;
4236 // Compute initial pad
4238 MD5Update(&ctx
, type
, 2);
4239 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4240 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4241 MD5Final(digest
, &ctx
);
4243 // Get hidden length
4244 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4246 // Keep these for later use
4247 working_vector
[0] = *cursor
;
4248 working_vector
[1] = *(cursor
+ 1);
4251 if (hidden_length
> length
- 8)
4253 LOG(1, 0, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4257 /* Decrypt remainder */
4259 todo
= hidden_length
;
4262 working_vector
[done
] = *cursor
;
4263 *output
= digest
[done
] ^ *cursor
;
4268 if (done
== 16 && todo
)
4270 // Compute new digest
4273 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4274 MD5Update(&ctx
, &working_vector
, 16);
4275 MD5Final(digest
, &ctx
);
4279 return hidden_length
+ 6;