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.42 2004/11/05 02:25:25 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"
53 struct configt
*config
= NULL
; // all configuration
54 int tunfd
= -1; // tun interface file handle. (network device)
55 int udpfd
= -1; // UDP file handle
56 int controlfd
= -1; // Control signal handle
57 int snoopfd
= -1; // UDP file handle for sending out intercept data
58 int *radfds
= NULL
; // RADIUS requests file handles
59 int ifrfd
= -1; // File descriptor for routing, etc
60 time_t basetime
= 0; // base clock
61 char hostname
[1000] = ""; // us.
62 int tunidx
; // ifr_ifindex of tun device
63 u32 sessionid
= 0; // session id for radius accounting
64 int syslog_log
= 0; // are we logging to syslog
65 FILE *log_stream
= NULL
; // file handle for direct logging (i.e. direct into file, not via syslog).
66 extern int cluster_sockfd
; // Intra-cluster communications socket.
67 u32 last_id
= 0; // Last used PPP SID. Can I kill this?? -- mo
68 int clifd
= 0; // Socket listening for CLI connections.
70 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
71 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
73 static void *ip_hash
[256]; // Mapping from IP address to session structures.
75 u32 udp_tx
= 0, udp_rx
= 0, udp_rx_pkt
= 0; // Global traffic counters.
76 u32 eth_tx
= 0, eth_rx
= 0, eth_rx_pkt
= 0;
77 u32 ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
78 time_t time_now
= 0; // Current time in seconds since epoch.
79 char time_now_string
[64] = {0}; // Current time as a string.
80 char main_quit
= 0; // True if we're in the process of exiting.
81 char *_program_name
= NULL
;
82 linked_list
*loaded_plugins
;
83 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
87 struct bgp_peer
*bgp_peers
= 0;
88 struct bgp_route_list
*bgp_routes
= 0;
89 int bgp_configured
= 0;
92 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
93 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(struct configt, MEMBER), membersize(struct configt, MEMBER), TYPE }
95 struct config_descriptt config_values
[] = {
96 CONFIG("debug", debug
, INT
),
97 CONFIG("log_file", log_filename
, STRING
),
98 CONFIG("pid_file", pid_file
, STRING
),
99 CONFIG("l2tp_secret", l2tpsecret
, STRING
),
100 CONFIG("primary_dns", default_dns1
, IP
),
101 CONFIG("secondary_dns", default_dns2
, IP
),
102 CONFIG("save_state", save_state
, BOOL
),
103 CONFIG("primary_radius", radiusserver
[0], IP
),
104 CONFIG("secondary_radius", radiusserver
[1], IP
),
105 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
106 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
107 CONFIG("radius_accounting", radius_accounting
, BOOL
),
108 CONFIG("radius_secret", radiussecret
, STRING
),
109 CONFIG("bind_address", bind_address
, IP
),
110 CONFIG("send_garp", send_garp
, BOOL
),
111 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
112 CONFIG("throttle_buckets", num_tbfs
, INT
),
113 CONFIG("accounting_dir", accounting_dir
, STRING
),
114 CONFIG("setuid", target_uid
, INT
),
115 CONFIG("dump_speed", dump_speed
, BOOL
),
116 CONFIG("cleanup_interval", cleanup_interval
, INT
),
117 CONFIG("multi_read_count", multi_read_count
, INT
),
118 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
119 CONFIG("lock_pages", lock_pages
, BOOL
),
120 CONFIG("icmp_rate", icmp_rate
, INT
),
121 CONFIG("cluster_address", cluster_address
, IP
),
122 CONFIG("cluster_interface", cluster_interface
, STRING
),
123 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
124 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
126 CONFIG("as_number", as_number
, SHORT
),
127 CONFIG("bgp_peer1", bgp_peer
[0], STRING
),
128 CONFIG("bgp_peer1_as", bgp_peer_as
[0], SHORT
),
129 CONFIG("bgp_peer2", bgp_peer
[1], STRING
),
130 CONFIG("bgp_peer2_as", bgp_peer_as
[1], SHORT
),
135 char *plugin_functions
[] = {
142 "plugin_new_session",
143 "plugin_kill_session",
145 "plugin_radius_response",
146 "plugin_become_master",
147 "plugin_new_session_master",
150 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
152 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
153 sessiont
*session
= NULL
; // Array of session structures.
154 sessioncountt
*sess_count
= NULL
; // Array of partial per-session traffic counters.
155 radiust
*radius
= NULL
; // Array of radius structures.
156 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
157 controlt
*controlfree
= 0;
158 struct Tstats
*_statistics
= NULL
;
160 struct Tringbuffer
*ringbuffer
= NULL
;
163 void sigalrm_handler(int);
164 void sighup_handler(int);
165 void sigterm_handler(int);
166 void sigquit_handler(int);
167 void sigchild_handler(int);
168 void read_config_file();
172 tunnelidt
new_tunnel();
173 void update_config();
174 int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
);
176 static void cache_ipmap(ipt ip
, int s
);
177 static void uncache_ipmap(ipt ip
);
179 // return internal time (10ths since process startup)
184 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
187 // work out a retry time based on try number
188 // This is a straight bounded exponential backoff.
189 // Maximum re-try time is 32 seconds. (2^5).
190 clockt
backoff(u8
try)
192 if (try > 5) try = 5; // max backoff
193 return now() + 10 * (1 << try);
198 // Log a debug message.
200 void _log(int level
, ipt address
, sessionidt s
, tunnelidt t
, const char *format
, ...)
202 static char message
[65536] = {0};
203 static char message2
[65536] = {0};
209 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
210 ringbuffer
->tail
= 0;
211 if (ringbuffer
->tail
== ringbuffer
->head
)
212 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
213 ringbuffer
->head
= 0;
215 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
216 ringbuffer
->buffer
[ringbuffer
->tail
].address
= address
;
217 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
218 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
219 va_start(ap
, format
);
220 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
225 if (config
->debug
< level
) return;
227 va_start(ap
, format
);
230 vsnprintf(message2
, 65535, format
, ap
);
231 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
232 fprintf(log_stream
, "%s", message
);
236 vsnprintf(message2
, 65535, format
, ap
);
237 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
238 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
243 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
246 const u8
*d
= (const u8
*)data
;
248 if (config
->debug
< level
) return;
250 // No support for log_hex to syslog
253 _log(level
, 0, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
254 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
256 for (i
= 0; i
< maxsize
; )
258 fprintf(log_stream
, "%4X: ", i
);
259 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
261 fprintf(log_stream
, "%02X ", d
[j
]);
263 fputs(": ", log_stream
);
266 for (; j
< i
+ 16; j
++)
268 fputs(" ", log_stream
);
270 fputs(": ", log_stream
);
273 fputs(" ", log_stream
);
274 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
276 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
277 fputc(d
[j
], log_stream
);
279 fputc('.', log_stream
);
282 fputs(" ", log_stream
);
286 fputs("\n", log_stream
);
290 setbuf(log_stream
, NULL
);
297 // This adds it to the routing table, advertises it
298 // via iBGP if enabled, and stuffs it into the
299 // 'sessionbyip' cache.
301 // 'ip' and 'mask' must be in _host_ order.
303 void routeset(sessionidt s
, ipt ip
, ipt mask
, ipt gw
, u8 add
)
308 if (!mask
) mask
= 0xffffffff;
310 ip
&= mask
; // Force the ip to be the first one in the route.
312 memset(&r
, 0, sizeof(r
));
313 r
.rt_dev
= config
->tundevice
;
314 r
.rt_dst
.sa_family
= AF_INET
;
315 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
316 r
.rt_gateway
.sa_family
= AF_INET
;
317 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
318 r
.rt_genmask
.sa_family
= AF_INET
;
319 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
320 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
322 r
.rt_flags
|= RTF_GATEWAY
;
323 else if (mask
== 0xffffffff)
324 r
.rt_flags
|= RTF_HOST
;
326 log(1, ip
, 0, 0, "Route %s %u.%u.%u.%u/%u.%u.%u.%u %u.%u.%u.%u\n",
328 ip
>> 24, ip
>> 16 & 0xff, ip
>> 8 & 0xff, ip
& 0xff,
329 mask
>> 24, mask
>> 16 & 0xff, mask
>> 8 & 0xff, mask
& 0xff,
330 gw
>> 24, gw
>> 16 & 0xff, gw
>> 8 & 0xff, gw
& 0xff);
332 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
333 log(0, 0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
337 bgp_add_route(htonl(ip
), htonl(mask
));
339 bgp_del_route(htonl(ip
), htonl(mask
));
342 // Add/Remove the IPs to the 'sessionbyip' cache.
343 // Note that we add the zero address in the case of
344 // a network route. Roll on CIDR.
346 // Note that 's == 0' implies this is the address pool.
347 // We still cache it here, because it will pre-fill
348 // the malloc'ed tree.
352 if (!add
) // Are we deleting a route?
353 s
= 0; // Caching the session as '0' is the same as uncaching.
355 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
361 // Set up TUN interface
365 struct sockaddr_in sin
= {0};
366 memset(&ifr
, 0, sizeof(ifr
));
367 ifr
.ifr_flags
= IFF_TUN
;
369 tunfd
= open(TUNDEVICE
, O_RDWR
);
372 log(0, 0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
376 int flags
= fcntl(tunfd
, F_GETFL
, 0);
377 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
379 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
381 log(0, 0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
384 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
385 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
386 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
388 sin
.sin_family
= AF_INET
;
389 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
390 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
392 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
394 log(0, 0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
397 /* Bump up the qlen to deal with bursts from the network */
399 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
401 log(0, 0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
404 ifr
.ifr_flags
= IFF_UP
;
405 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
407 log(0, 0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
410 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
412 log(0, 0, 0, 0, "Error setting tun ifindex: %s\n", strerror(errno
));
415 tunidx
= ifr
.ifr_ifindex
;
422 struct sockaddr_in addr
;
425 memset(&addr
, 0, sizeof(addr
));
426 addr
.sin_family
= AF_INET
;
427 addr
.sin_port
= htons(L2TPPORT
);
428 addr
.sin_addr
.s_addr
= config
->bind_address
;
429 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
430 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
432 int flags
= fcntl(udpfd
, F_GETFL
, 0);
433 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
435 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
437 log(0, 0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
440 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
443 memset(&addr
, 0, sizeof(addr
));
444 addr
.sin_family
= AF_INET
;
445 addr
.sin_port
= htons(1702);
446 controlfd
= socket(AF_INET
, SOCK_DGRAM
, 17);
447 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
448 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
450 log(0, 0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
456 // Find session by IP, < 1 for not found
458 // Confusingly enough, this 'ip' must be
459 // in _network_ order. This being the common
460 // case when looking it up from IP packet headers.
462 // We actually use this cache for two things.
463 // #1. For used IP addresses, this maps to the
464 // session ID that it's used by.
465 // #2. For un-used IP addresses, this maps to the
466 // index into the pool table that contains that
470 int lookup_ipmap(ipt ip
)
473 char **d
= (char **) ip_hash
;
476 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
477 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
478 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
480 s
= (ipt
) d
[(size_t) *a
];
484 sessionidt
sessionbyip(ipt ip
)
486 int s
= lookup_ipmap(ip
);
487 CSTAT(call_sessionbyip
);
489 if (s
> 0 && s
< MAXSESSION
&& session
[s
].tunnel
)
495 // Take an IP address in HOST byte order and
496 // add it to the sessionid by IP cache.
498 // (It's actually cached in network order)
500 static void cache_ipmap(ipt ip
, int s
)
502 ipt nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char*)(&ip))[0]
504 char **d
= (char **) ip_hash
;
507 for (i
= 0; i
< 3; i
++)
509 if (!d
[(size_t) a
[i
]])
511 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof (void *))))
515 d
= (char **) d
[(size_t) a
[i
]];
518 d
[(size_t) a
[3]] = (char *)((int)s
);
521 log(4, ip
, s
, session
[s
].tunnel
, "Caching ip address %s\n", inet_toa(nip
));
523 log(4, ip
, 0, 0, "Un-caching ip address %s\n", inet_toa(nip
));
524 // else a map to an ip pool index.
527 static void uncache_ipmap(ipt ip
)
529 cache_ipmap(ip
, 0); // Assign it to the NULL session.
533 // CLI list to dump current ipcache.
535 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
537 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
541 if (CLI_HELP_REQUESTED
)
542 return CLI_HELP_NO_ARGS
;
544 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
546 for (i
= 0; i
< 256; ++i
)
551 for (j
= 0; j
< 256; ++j
)
556 for (k
= 0; k
< 256; ++k
)
561 for (l
= 0; l
< 256; ++l
)
565 cli_print(cli
, "%7d %d.%d.%d.%d", (int) g
[l
], i
, j
, k
, l
);
571 cli_print(cli
, "%d entries in cache", count
);
576 // Find session by username, 0 for not found
577 // walled garden users aren't authenticated, so the username is
578 // reasonably useless. Ignore them to avoid incorrect actions
580 // This is VERY inefficent. Don't call it often. :)
582 sessionidt
sessionbyuser(char *username
)
585 CSTAT(call_sessionbyuser
);
587 for (s
= 1; s
< MAXSESSION
; ++s
)
589 if (session
[s
].walled_garden
)
590 continue; // Skip walled garden users.
592 if (!strncmp(session
[s
].user
, username
, 128))
596 return 0; // Not found.
599 void send_garp(ipt ip
)
605 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
608 log(0, 0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
611 memset(&ifr
, 0, sizeof(ifr
));
612 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
613 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
615 log(0, 0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
619 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
620 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
622 log(0, 0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
627 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
630 // Find session by username, 0 for not found
631 sessiont
*sessiontbysessionidt(sessionidt s
)
633 if (!s
|| s
> MAXSESSION
) return NULL
;
637 sessionidt
sessionidtbysessiont(sessiont
*s
)
639 sessionidt val
= s
-session
;
640 if (s
< session
|| val
> MAXSESSION
) return 0;
644 // actually send a control message for a specific tunnel
645 void tunnelsend(u8
* buf
, u16 l
, tunnelidt t
)
647 struct sockaddr_in addr
;
649 CSTAT(call_tunnelsend
);
653 static int backtrace_count
= 0;
654 log(0, 0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
655 STAT(tunnel_tx_errors
);
656 log_backtrace(backtrace_count
, 5)
662 static int backtrace_count
= 0;
663 log(1, 0, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
664 log_backtrace(backtrace_count
, 5)
665 STAT(tunnel_tx_errors
);
668 memset(&addr
, 0, sizeof(addr
));
669 addr
.sin_family
= AF_INET
;
670 *(u32
*) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
671 addr
.sin_port
= htons(tunnel
[t
].port
);
673 // sequence expected, if sequence in message
674 if (*buf
& 0x08) *(u16
*) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
676 // If this is a control message, deal with retries
679 tunnel
[t
].last
= time_now
; // control message sent
680 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
681 if (tunnel
[t
].try > 1)
683 STAT(tunnel_retries
);
684 log(3, tunnel
[t
].ip
, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
688 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
690 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",
691 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
692 STAT(tunnel_tx_errors
);
696 log_hex(5, "Send Tunnel Data", buf
, l
);
697 STAT(tunnel_tx_packets
);
698 INC_STAT(tunnel_tx_bytes
, l
);
702 // Tiny helper function to write data to
705 int tun_write(u8
* data
, int size
)
707 return write(tunfd
, data
, size
);
710 // process outgoing (to tunnel) IP
712 void processipout(u8
* buf
, int len
)
719 char * data
= buf
; // Keep a copy of the originals.
724 CSTAT(call_processipout
);
726 if (len
< MIN_IP_SIZE
)
728 log(1, 0, 0, 0, "Short IP, %d bytes\n", len
);
729 STAT(tunnel_tx_errors
);
734 log(1, 0, 0, 0, "Oversize IP packet %d bytes\n", len
);
735 STAT(tunnel_tx_errors
);
739 // Skip the tun header
743 // Got an IP header now
744 if (*(u8
*)(buf
) >> 4 != 4)
746 log(1, 0, 0, 0, "IP: Don't understand anything except IPv4\n");
750 ip
= *(u32
*)(buf
+ 16);
751 if (!(s
= sessionbyip(ip
)))
753 // Is this a packet for a session that doesn't exist?
754 static int rate
= 0; // Number of ICMP packets we've sent this second.
755 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
757 if (last
!= time_now
)
763 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
765 log(4, 0, 0, 0, "IP: Sending ICMP host unreachable to %s\n", inet_toa(*(u32
*)(buf
+ 12)));
766 host_unreachable(*(u32
*)(buf
+ 12), *(u16
*)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
770 t
= session
[s
].tunnel
;
775 // Are we throttling this session?
776 if (config
->cluster_iam_master
)
777 tbf_queue_packet(sp
->tbf_out
, data
, size
);
779 master_throttle_packet(sp
->tbf_out
, data
, size
);
782 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
784 // We are walled-gardening this
785 master_garden_packet(s
, data
, size
);
789 // Snooping this session, send it to intercept box
790 if (sp
->snoop_ip
&& sp
->snoop_port
)
791 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
793 log(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
795 // Add on L2TP header
797 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
800 log(3, session
[s
].ip
, s
, t
, "failed to send packet in processipout.\n");
803 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
806 sp
->cout
+= len
; // byte count
807 sp
->total_cout
+= len
; // byte count
810 sess_count
[s
].cout
+= len
; // To send to master..
814 // Helper routine for the TBF filters.
815 // Used to send queued data in to the user!
817 void send_ipout(sessionidt s
, u8
*buf
, int len
)
825 if (len
< 0 || len
> MAXETHER
)
827 log(1,0,0,0, "Odd size IP packet: %d bytes\n", len
);
831 // Skip the tun header
835 ip
= *(u32
*)(buf
+ 16);
839 t
= session
[s
].tunnel
;
842 log(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
844 // Snooping this session.
845 if (sp
->snoop_ip
&& sp
->snoop_port
)
846 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
848 // Add on L2TP header
850 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
853 log(3, session
[s
].ip
, s
, t
, "failed to send packet in send_ipout.\n");
856 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
858 sp
->cout
+= len
; // byte count
859 sp
->total_cout
+= len
; // byte count
862 sess_count
[s
].cout
+= len
; // To send to master..
865 // add an AVP (16 bit)
866 void control16(controlt
* c
, u16 avp
, u16 val
, u8 m
)
868 u16 l
= (m
? 0x8008 : 0x0008);
869 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
870 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
871 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
872 *(u16
*) (c
->buf
+ c
->length
+ 6) = htons(val
);
876 // add an AVP (32 bit)
877 void control32(controlt
* c
, u16 avp
, u32 val
, u8 m
)
879 u16 l
= (m
? 0x800A : 0x000A);
880 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
881 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
882 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
883 *(u32
*) (c
->buf
+ c
->length
+ 6) = htonl(val
);
887 // add an AVP (32 bit)
888 void controls(controlt
* c
, u16 avp
, char *val
, u8 m
)
890 u16 l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
891 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
892 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
893 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
894 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
895 c
->length
+= 6 + strlen(val
);
899 void controlb(controlt
* c
, u16 avp
, char *val
, unsigned int len
, u8 m
)
901 u16 l
= ((m
? 0x8000 : 0) + len
+ 6);
902 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
903 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
904 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
905 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
906 c
->length
+= 6 + len
;
909 // new control connection
910 controlt
*controlnew(u16 mtype
)
914 c
= malloc(sizeof(controlt
));
918 controlfree
= c
->next
;
922 *(u16
*) (c
->buf
+ 0) = htons(0xC802); // flags/ver
924 control16(c
, 0, mtype
, 1);
928 // send zero block if nothing is waiting
930 void controlnull(tunnelidt t
)
933 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
936 *(u16
*) (buf
+ 0) = htons(0xC802); // flags/ver
937 *(u16
*) (buf
+ 2) = htons(12); // length
938 *(u16
*) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
939 *(u16
*) (buf
+ 6) = htons(0); // session
940 *(u16
*) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
941 *(u16
*) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
942 tunnelsend(buf
, 12, t
);
945 // add a control message to a tunnel, and send if within window
946 void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
948 *(u16
*) (c
->buf
+ 2) = htons(c
->length
); // length
949 *(u16
*) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
950 *(u16
*) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
951 *(u16
*) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
952 tunnel
[t
].ns
++; // advance sequence
953 // link in message in to queue
954 if (tunnel
[t
].controlc
)
955 tunnel
[t
].controle
->next
= c
;
957 tunnel
[t
].controls
= c
;
958 tunnel
[t
].controle
= c
;
959 tunnel
[t
].controlc
++;
960 // send now if space in window
961 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
963 tunnel
[t
].try = 0; // first send
964 tunnelsend(c
->buf
, c
->length
, t
);
969 // Throttle or Unthrottle a session
971 // Throttle the data from/to through a session to no more than
972 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
975 // If either value is -1, the current value is retained for that
978 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
980 if (!session
[s
].tunnel
)
981 return; // No-one home.
983 if (!*session
[s
].user
)
984 return; // User not logged in
988 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
989 if (session
[s
].tbf_in
)
990 free_tbf(session
[s
].tbf_in
);
993 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
995 session
[s
].tbf_in
= 0;
997 session
[s
].throttle_in
= rate_in
;
1002 int bytes
= rate_out
* 1024 / 8;
1003 if (session
[s
].tbf_out
)
1004 free_tbf(session
[s
].tbf_out
);
1007 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1009 session
[s
].tbf_out
= 0;
1011 session
[s
].throttle_out
= rate_out
;
1015 // start tidy shutdown of session
1016 void sessionshutdown(sessionidt s
, char *reason
)
1018 int dead
= session
[s
].die
;
1019 int walled_garden
= session
[s
].walled_garden
;
1022 CSTAT(call_sessionshutdown
);
1024 if (!session
[s
].tunnel
)
1026 log(3, session
[s
].ip
, s
, session
[s
].tunnel
, "Called sessionshutdown on a session with no tunnel.\n");
1027 return; // not a live session
1031 log(2, 0, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1033 session
[s
].die
= now() + 150; // Clean up in 15 seconds
1036 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1037 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1040 // RADIUS Stop message
1041 if (session
[s
].opened
&& !walled_garden
&& !dead
)
1043 u16 r
= session
[s
].radius
;
1046 if (!(r
= radiusnew(s
)))
1048 log(1, 0, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1049 STAT(radius_overflow
);
1054 for (n
= 0; n
< 15; n
++)
1055 radius
[r
].auth
[n
] = rand();
1058 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1059 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1063 { // IP allocated, clear and unroute
1065 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1067 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, session
[s
].ip
, 0);
1068 session
[s
].route
[r
].ip
= 0;
1071 if (session
[s
].ip_pool_index
== -1) // static ip
1073 routeset(s
, session
[s
].ip
, 0, 0, 0); // Delete route.
1080 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1081 throttle_session(s
, 0, 0);
1084 controlt
*c
= controlnew(14); // sending CDN
1085 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1086 control16(c
, 14, s
, 1); // assigned session (our end)
1087 controladd(c
, session
[s
].tunnel
, s
); // send the message
1090 cluster_send_session(s
);
1093 void sendipcp(tunnelidt t
, sessionidt s
)
1096 u16 r
= session
[s
].radius
;
1099 CSTAT(call_sendipcp
);
1104 if (radius
[r
].state
!= RADIUSIPCP
)
1106 radius
[r
].state
= RADIUSIPCP
;
1110 radius
[r
].retry
= backoff(radius
[r
].try++);
1111 if (radius
[r
].try > 10)
1113 radiusclear(r
, s
); // Clear radius session.
1114 sessionshutdown(s
, "No reply on IPCP");
1118 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1121 log(3, session
[s
].ip
, s
, t
, "failed to send packet in sendipcp.\n");
1126 q
[1] = r
<< RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1127 *(u16
*) (q
+ 2) = htons(10);
1130 *(u32
*) (q
+ 6) = config
->bind_address
? config
->bind_address
: my_address
; // send my IP
1131 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1132 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1135 // kill a session now
1136 void sessionkill(sessionidt s
, char *reason
)
1139 CSTAT(call_sessionkill
);
1141 session
[s
].die
= now();
1142 sessionshutdown(s
, reason
); // close radius/routes, etc.
1143 if (session
[s
].radius
)
1144 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1146 log(2, 0, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1148 memset(&session
[s
], 0, sizeof(session
[s
]));
1149 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1150 session
[s
].next
= sessionfree
;
1152 cli_session_actions
[s
].action
= 0;
1153 cluster_send_session(s
);
1156 // kill a tunnel now
1157 void tunnelkill(tunnelidt t
, char *reason
)
1162 CSTAT(call_tunnelkill
);
1164 tunnel
[t
].state
= TUNNELDIE
;
1166 // free control messages
1167 while ((c
= tunnel
[t
].controls
))
1169 controlt
* n
= c
->next
;
1170 tunnel
[t
].controls
= n
;
1171 tunnel
[t
].controlc
--;
1172 c
->next
= controlfree
;
1176 for (s
= 1; s
< MAXSESSION
; s
++)
1177 if (session
[s
].tunnel
== t
)
1178 sessionkill(s
, reason
);
1182 log(1, 0, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1183 cli_tunnel_actions
[s
].action
= 0;
1184 cluster_send_tunnel(t
);
1187 // shut down a tunnel cleanly
1188 void tunnelshutdown(tunnelidt t
, char *reason
)
1192 CSTAT(call_tunnelshutdown
);
1194 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1196 // never set up, can immediately kill
1197 tunnelkill(t
, reason
);
1200 log(1, 0, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1203 for (s
= 1; s
< MAXSESSION
; s
++)
1204 if (session
[s
].tunnel
== t
)
1205 sessionkill(s
, reason
);
1207 tunnel
[t
].state
= TUNNELDIE
;
1208 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
1209 cluster_send_tunnel(t
);
1210 // TBA - should we wait for sessions to stop?
1212 controlt
*c
= controlnew(4); // sending StopCCN
1213 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message
1214 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1215 controladd(c
, t
, 0); // send the message
1219 // read and process packet on tunnel (UDP)
1220 void processudp(u8
* buf
, int len
, struct sockaddr_in
*addr
)
1222 char *chapresponse
= NULL
;
1223 u16 l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1227 CSTAT(call_processudp
);
1231 log_hex(5, "UDP Data", buf
, len
);
1232 STAT(tunnel_rx_packets
);
1233 INC_STAT(tunnel_rx_bytes
, len
);
1236 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Short UDP, %d bytes\n", len
);
1237 STAT(tunnel_rx_errors
);
1240 if ((buf
[1] & 0x0F) != 2)
1242 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1243 STAT(tunnel_rx_errors
);
1248 l
= ntohs(*(u16
*) p
);
1251 t
= ntohs(*(u16
*) p
);
1253 s
= ntohs(*(u16
*) p
);
1255 if (s
>= MAXSESSION
)
1257 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid session ID\n");
1258 STAT(tunnel_rx_errors
);
1263 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid tunnel ID\n");
1264 STAT(tunnel_rx_errors
);
1269 ns
= ntohs(*(u16
*) p
);
1271 nr
= ntohs(*(u16
*) p
);
1276 u16 o
= ntohs(*(u16
*) p
);
1281 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad length %d>%d\n", (p
- buf
), l
);
1282 STAT(tunnel_rx_errors
);
1288 u16 message
= 0xFFFF; // message type
1290 u8 mandatorymessage
= 0;
1291 u8 chap
= 0; // if CHAP being used
1292 u16 asession
= 0; // assigned session
1293 u32 amagic
= 0; // magic number
1294 u8 aflags
= 0; // flags from last LCF
1295 u16 version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1296 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1297 char called
[MAXTEL
] = ""; // called number
1298 char calling
[MAXTEL
] = ""; // calling number
1300 if (!config
->cluster_iam_master
)
1302 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1306 if ((*buf
& 0xCA) != 0xC8)
1308 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad control header %02X\n", *buf
);
1309 STAT(tunnel_rx_errors
);
1312 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",
1313 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1314 // if no tunnel specified, assign one
1320 // Is this a duplicate of the first packet? (SCCRQ)
1322 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1324 if (tunnel
[i
].state
!= TUNNELOPENING
||
1325 tunnel
[i
].ip
!= ntohl(*(ipt
*) & addr
->sin_addr
) ||
1326 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1335 if (!(t
= new_tunnel()))
1337 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "No more tunnels\n");
1338 STAT(tunnel_overflow
);
1342 tunnel
[t
].ip
= ntohl(*(ipt
*) & addr
->sin_addr
);
1343 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1344 tunnel
[t
].window
= 4; // default window
1345 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
);
1346 STAT(tunnel_created
);
1349 // This is used to time out old tunnels
1350 tunnel
[t
].lastrec
= time_now
;
1352 // check sequence of this message
1354 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1355 // some to clear maybe?
1356 while (tunnel
[t
].controlc
&& (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1358 controlt
*c
= tunnel
[t
].controls
;
1359 tunnel
[t
].controls
= c
->next
;
1360 tunnel
[t
].controlc
--;
1361 c
->next
= controlfree
;
1364 tunnel
[t
].try = 0; // we have progress
1367 // If the 'ns' just received is not the 'nr' we're
1368 // expecting, just send an ack and drop it.
1370 // if 'ns' is less, then we got a retransmitted packet.
1371 // if 'ns' is greater than missed a packet. Either way
1372 // we should ignore it.
1373 if (ns
!= tunnel
[t
].nr
)
1375 // is this the sequence we were expecting?
1376 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
);
1377 STAT(tunnel_rx_errors
);
1379 if (l
) // Is this not a ZLB?
1383 // receiver advance (do here so quoted correctly in any sends below)
1384 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1385 if (skip
< 0) skip
= 0;
1386 if (skip
< tunnel
[t
].controlc
)
1388 // some control packets can now be sent that were previous stuck out of window
1389 int tosend
= tunnel
[t
].window
- skip
;
1390 controlt
*c
= tunnel
[t
].controls
;
1398 tunnel
[t
].try = 0; // first send
1399 tunnelsend(c
->buf
, c
->length
, t
);
1404 if (!tunnel
[t
].controlc
)
1405 tunnel
[t
].retry
= 0; // caught up
1408 { // if not a null message
1410 while (l
&& !(fatal
& 0x80))
1412 u16 n
= (ntohs(*(u16
*) p
) & 0x3FF);
1419 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Invalid length in AVP\n");
1420 STAT(tunnel_rx_errors
);
1427 // handle hidden AVPs
1428 if (!*config
->l2tpsecret
)
1430 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1434 if (!session
[s
].random_vector_length
)
1436 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no random vector.\n");
1440 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP\n");
1442 n
= unhide_avp(b
, t
, s
, n
);
1451 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1458 log(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown AVP vendor %d\n", ntohs(*(u16
*) (b
)));
1463 mtype
= ntohs(*(u16
*) (b
));
1467 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1470 case 0: // message type
1471 message
= ntohs(*(u16
*) b
);
1472 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Message type = %d (%s)\n", *b
,
1473 l2tp_message_types
[message
]);
1474 mandatorymessage
= flags
;
1476 case 1: // result code
1478 u16 rescode
= ntohs(*(u16
*)(b
));
1479 const char* resdesc
= "(unknown)";
1482 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1483 resdesc
= stopccn_result_codes
[rescode
];
1485 else if (message
== 14)
1487 if (rescode
<= MAX_CDN_RESULT_CODE
)
1488 resdesc
= cdn_result_codes
[rescode
];
1491 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Result Code %d: %s\n",
1495 u16 errcode
= ntohs(*(u16
*)(b
+ 2));
1496 const char* errdesc
= "(unknown)";
1497 if (errcode
<= MAX_ERROR_CODE
)
1498 errdesc
= error_codes
[errcode
];
1499 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error Code %d: %s\n",
1503 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error String: %.*s\n",
1509 case 2: // protocol version
1511 version
= ntohs(*(u16
*) (b
));
1512 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Protocol version = %d\n", version
);
1513 if (version
&& version
!= 0x0100)
1514 { // allow 0.0 and 1.0
1515 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Bad protocol version %04X\n",
1522 case 3: // framing capabilities
1523 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Framing capabilities\n");
1525 case 4: // bearer capabilities
1526 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Bearer capabilities\n");
1528 case 5: // tie breaker
1529 // We never open tunnels, so we don't care about tie breakers
1530 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Tie breaker\n");
1532 case 6: // firmware revision
1533 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Firmware revision\n");
1535 case 7: // host name
1536 memset(tunnel
[t
].hostname
, 0, 128);
1537 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1538 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1539 // TBA - to send to RADIUS
1541 case 8: // vendor name
1542 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1543 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1544 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1546 case 9: // assigned tunnel
1547 tunnel
[t
].far
= ntohs(*(u16
*) (b
));
1548 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1550 case 10: // rx window
1551 tunnel
[t
].window
= ntohs(*(u16
*) (b
));
1552 if (!tunnel
[t
].window
)
1553 tunnel
[t
].window
= 1; // window of 0 is silly
1554 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1556 case 11: // Challenge
1558 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " LAC requested CHAP authentication for tunnel\n");
1559 build_chap_response(b
, 2, n
, &chapresponse
);
1562 case 13: // Response
1563 // Why did they send a response? We never challenge.
1564 log(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " received unexpected challenge response\n");
1567 case 14: // assigned session
1568 asession
= session
[s
].far
= ntohs(*(u16
*) (b
));
1569 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " assigned session = %d\n", asession
);
1571 case 15: // call serial number
1572 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " call serial number = %d\n", ntohl(*(u32
*)b
));
1574 case 18: // bearer type
1575 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " bearer type = %d\n", ntohl(*(u32
*)b
));
1578 case 19: // framing type
1579 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " framing type = %d\n", ntohl(*(u32
*)b
));
1582 case 21: // called number
1583 memset(called
, 0, MAXTEL
);
1584 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1585 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Called <%s>\n", called
);
1587 case 22: // calling number
1588 memset(calling
, 0, MAXTEL
);
1589 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1590 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Calling <%s>\n", calling
);
1594 case 24: // tx connect speed
1597 session
[s
].tx_connect_speed
= ntohl(*(u32
*)b
);
1601 // AS5300s send connect speed as a string
1603 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1604 session
[s
].tx_connect_speed
= atol(tmp
);
1606 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " TX connect speed <%u>\n",
1607 session
[s
].tx_connect_speed
);
1609 case 38: // rx connect speed
1612 session
[s
].rx_connect_speed
= ntohl(*(u32
*)b
);
1616 // AS5300s send connect speed as a string
1618 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1619 session
[s
].rx_connect_speed
= atol(tmp
);
1621 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " RX connect speed <%u>\n",
1622 session
[s
].rx_connect_speed
);
1624 case 25: // Physical Channel ID
1626 u32 tmp
= ntohl(*(u32
*)b
);
1627 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Physical Channel ID <%X>\n", tmp
);
1630 case 29: // Proxy Authentication Type
1632 u16 authtype
= ntohs(*(u16
*)b
);
1633 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Type %d (%s)\n",
1634 authtype
, authtypes
[authtype
]);
1635 requestchap
= (authtype
== 2);
1638 case 30: // Proxy Authentication Name
1640 char authname
[64] = {0};
1641 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1642 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Name (%s)\n",
1646 case 31: // Proxy Authentication Challenge
1648 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1649 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Challenge\n");
1652 case 32: // Proxy Authentication ID
1654 u16 authid
= ntohs(*(u16
*)(b
));
1655 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth ID (%d)\n",
1657 if (session
[s
].radius
)
1658 radius
[session
[s
].radius
].id
= authid
;
1661 case 33: // Proxy Authentication Response
1663 char authresp
[64] = {0};
1664 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1665 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Response\n");
1668 case 27: // last send lcp
1669 { // find magic number
1670 u8
*p
= b
, *e
= p
+ n
;
1671 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1673 if (*p
== 5 && p
[1] == 6) // Magic-Number
1674 amagic
= ntohl(*(u32
*) (p
+ 2));
1675 else if (*p
== 3 && p
[1] == 5 && *(u16
*) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1677 else if (*p
== 7) // Protocol-Field-Compression
1678 aflags
|= SESSIONPFC
;
1679 else if (*p
== 8) // Address-and-Control-Field-Compression
1680 aflags
|= SESSIONACFC
;
1685 case 28: // last recv lcp confreq
1687 case 26: // Initial Received LCP CONFREQ
1689 case 39: // seq required - we control it as an LNS anyway...
1691 case 36: // Random Vector
1692 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1693 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1694 memcpy(session
[s
].random_vector
, b
, n
);
1695 session
[s
].random_vector_length
= n
;
1698 log(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Unknown AVP type %d\n", mtype
);
1705 tunnelshutdown(t
, "Unknown Mandatory AVP");
1709 case 1: // SCCRQ - Start Control Connection Request
1711 controlt
*c
= controlnew(2); // sending SCCRP
1712 control16(c
, 2, version
, 1); // protocol version
1713 control32(c
, 3, 3, 1); // framing
1714 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1715 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1716 control16(c
, 9, t
, 1); // assigned tunnel
1717 controladd(c
, t
, s
); // send the resply
1719 tunnel
[t
].state
= TUNNELOPENING
;
1722 tunnel
[t
].state
= TUNNELOPEN
;
1725 tunnel
[t
].state
= TUNNELOPEN
;
1726 controlnull(t
); // ack
1729 controlnull(t
); // ack
1730 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1731 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1734 controlnull(t
); // simply ACK
1748 STAT(session_overflow
);
1749 tunnelshutdown(t
, "No free sessions");
1757 sessionfree
= session
[s
].next
;
1758 memset(&session
[s
], 0, sizeof(session
[s
]));
1760 if (s
> config
->cluster_highest_sessionid
)
1761 config
->cluster_highest_sessionid
= s
;
1763 // make a RADIUS session
1764 if (!(r
= radiusnew(s
)))
1766 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "No free RADIUS sessions for ICRQ\n");
1767 sessionkill(s
, "no free RADIUS sesions");
1771 c
= controlnew(11); // sending ICRP
1772 session
[s
].id
= sessionid
++;
1773 session
[s
].opened
= time(NULL
);
1774 session
[s
].tunnel
= t
;
1775 session
[s
].far
= asession
;
1776 session
[s
].last_packet
= time_now
;
1777 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1778 control16(c
, 14, s
, 1); // assigned session
1779 controladd(c
, t
, s
); // send the reply
1781 // Generate a random challenge
1783 for (n
= 0; n
< 15; n
++)
1784 radius
[r
].auth
[n
] = rand();
1786 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1787 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1788 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1789 STAT(session_created
);
1796 if (amagic
== 0) amagic
= time_now
;
1797 session
[s
].magic
= amagic
; // set magic number
1798 session
[s
].l2tp_flags
= aflags
; // set flags received
1799 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1800 controlnull(t
); // ack
1801 // In CHAP state, request PAP instead
1806 controlnull(t
); // ack
1807 sessionshutdown(s
, "Closed (Received CDN)");
1810 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Missing message type\n");
1813 STAT(tunnel_rx_errors
);
1814 if (mandatorymessage
& 0x80)
1815 tunnelshutdown(t
, "Unknown message");
1817 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown message type %d\n", message
);
1820 if (chapresponse
) free(chapresponse
);
1821 cluster_send_tunnel(t
);
1825 log(4, 0, s
, t
, " Got a ZLB ack\n");
1832 log_hex(5, "Receive Tunnel Data", p
, l
);
1833 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1834 { // HDLC address header, discard
1840 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Short ppp length %d\n", l
);
1841 STAT(tunnel_rx_errors
);
1851 prot
= ntohs(*(u16
*) p
);
1856 if (s
&& !session
[s
].tunnel
) // Is something wrong??
1858 if (!config
->cluster_iam_master
)
1860 // Pass it off to the master to deal with..
1861 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1866 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "UDP packet contains session %d "
1867 "but no session[%d].tunnel exists (LAC said"
1868 " tunnel = %d). Dropping packet.\n", s
, s
, t
);
1869 STAT(tunnel_rx_errors
);
1875 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1876 // I'm pretty sure this isn't right -- mo.
1877 // return; // closing session, PPP not processed
1881 session
[s
].last_packet
= time_now
;
1882 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1883 processpap(t
, s
, p
, l
);
1885 else if (prot
== PPPCHAP
)
1887 session
[s
].last_packet
= time_now
;
1888 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1889 processchap(t
, s
, p
, l
);
1891 else if (prot
== PPPLCP
)
1893 session
[s
].last_packet
= time_now
;
1894 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1895 processlcp(t
, s
, p
, l
);
1897 else if (prot
== PPPIPCP
)
1899 session
[s
].last_packet
= time_now
;
1900 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1901 processipcp(t
, s
, p
, l
);
1903 else if (prot
== PPPCCP
)
1905 session
[s
].last_packet
= time_now
;
1906 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1907 processccp(t
, s
, p
, l
);
1909 else if (prot
== PPPIP
)
1911 session
[s
].last_packet
= time_now
;
1912 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
1914 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1917 processipin(t
, s
, p
, l
);
1921 STAT(tunnel_rx_errors
);
1922 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown PPP protocol %04X\n", prot
);
1927 // read and process packet on tun
1928 void processtun(u8
* buf
, int len
)
1930 log_hex(5, "Receive TUN Data", buf
, len
);
1931 STAT(tun_rx_packets
);
1932 INC_STAT(tun_rx_bytes
, len
);
1934 CSTAT(call_processtun
);
1940 log(1, 0, 0, 0, "Short tun packet %d bytes\n", len
);
1941 STAT(tun_rx_errors
);
1945 if (*(u16
*) (buf
+ 2) == htons(PKTIP
)) // IP
1946 processipout(buf
, len
);
1951 // Maximum number of actions to complete.
1952 // This is to avoid sending out too many packets
1954 #define MAX_ACTIONS 500
1956 int regular_cleanups(void)
1958 static sessionidt s
= 0; // Next session to check for actions on.
1962 static clockt next_acct
= 0;
1965 log(3, 0, 0, 0, "Begin regular cleanup\n");
1967 for (r
= 1; r
< MAXRADIUS
; r
++)
1969 if (!radius
[r
].state
)
1971 if (radius
[r
].retry
)
1973 if (radius
[r
].retry
<= TIME
)
1976 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
1978 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
1980 // check for expired tunnels
1981 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
1983 STAT(tunnel_timeout
);
1984 tunnelkill(t
, "Expired");
1987 // check for message resend
1988 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
1990 // resend pending messages as timeout on reply
1991 if (tunnel
[t
].retry
<= TIME
)
1993 controlt
*c
= tunnel
[t
].controls
;
1994 u8 w
= tunnel
[t
].window
;
1995 tunnel
[t
].try++; // another try
1996 if (tunnel
[t
].try > 5)
1997 tunnelkill(t
, "Timeout on control message"); // game over
2001 tunnelsend(c
->buf
, c
->length
, t
);
2007 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2009 controlt
*c
= controlnew(6); // sending HELLO
2010 controladd(c
, t
, 0); // send the message
2011 log(3, tunnel
[t
].ip
, 0, t
, "Sending HELLO message\n");
2014 // Check for tunnel changes requested from the CLI
2015 if ((a
= cli_tunnel_actions
[t
].action
))
2017 cli_tunnel_actions
[t
].action
= 0;
2018 if (a
& CLI_TUN_KILL
)
2020 log(2, tunnel
[t
].ip
, 0, t
, "Dropping tunnel by CLI\n");
2021 tunnelshutdown(t
, "Requested by administrator");
2028 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2031 if (s
> config
->cluster_highest_sessionid
)
2034 if (!session
[s
].tunnel
) // Session isn't in use
2037 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2039 // IPCP has not completed yet. Resend
2040 log(3, session
[s
].ip
, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2041 sendipcp(session
[s
].tunnel
, s
);
2044 // check for expired sessions
2045 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2047 sessionkill(s
, "Expired");
2048 if (++count
>= MAX_ACTIONS
) break;
2052 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2053 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2055 sessionkill(s
, "No response to LCP ECHO requests");
2056 STAT(session_timeout
);
2057 if (++count
>= MAX_ACTIONS
) break;
2061 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2062 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2064 u8 b
[MAXCONTROL
] = {0};
2066 u8
*q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2069 log(3, session
[s
].ip
, s
, t
, "failed to send ECHO packet.\n");
2074 *(u8
*)(q
+ 1) = (time_now
% 255); // ID
2075 *(u16
*)(q
+ 2) = htons(8); // Length
2076 *(u32
*)(q
+ 4) = 0; // Magic Number (not supported)
2078 log(4, session
[s
].ip
, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2079 (int)(time_now
- session
[s
].last_packet
));
2080 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2081 if (++count
>= MAX_ACTIONS
) break;
2084 // Check for actions requested from the CLI
2085 if ((a
= cli_session_actions
[s
].action
))
2089 cli_session_actions
[s
].action
= 0;
2090 if (a
& CLI_SESS_KILL
)
2092 log(2, 0, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2093 sessionshutdown(s
, "Requested by administrator");
2094 a
= 0; // dead, no need to check for other actions
2097 if (a
& CLI_SESS_NOSNOOP
)
2099 log(2, 0, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2100 session
[s
].snoop_ip
= 0;
2101 session
[s
].snoop_port
= 0;
2104 else if (a
& CLI_SESS_SNOOP
)
2106 log(2, 0, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2107 inet_toa(cli_session_actions
[s
].snoop_ip
), cli_session_actions
[s
].snoop_port
);
2109 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2110 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2114 if (a
& CLI_SESS_NOTHROTTLE
)
2116 log(2, 0, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2117 throttle_session(s
, 0, 0);
2120 else if (a
& CLI_SESS_THROTTLE
)
2122 log(2, 0, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2123 cli_session_actions
[s
].throttle_in
,
2124 cli_session_actions
[s
].throttle_out
);
2126 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2131 cluster_send_session(s
);
2133 if (++count
>= MAX_ACTIONS
) break;
2137 if (*config
->accounting_dir
&& next_acct
<= TIME
)
2139 // Dump accounting data
2140 next_acct
= TIME
+ ACCT_TIME
;
2144 if (count
>= MAX_ACTIONS
)
2145 return 1; // Didn't finish!
2147 log(3, 0, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count
, config
->cleanup_interval
);
2153 // Are we in the middle of a tunnel update, or radius
2156 int still_busy(void)
2159 static clockt last_talked
= 0;
2160 static clockt start_busy_wait
= 0;
2161 if (start_busy_wait
== 0)
2162 start_busy_wait
= TIME
;
2164 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2166 if (!tunnel
[i
].controlc
)
2169 if (last_talked
!= TIME
)
2171 log(2,0,0,0, "Tunnel %d still has un-acked control messages.\n", i
);
2177 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2178 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2180 log(1, 0, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2184 for (i
= 1; i
< MAXRADIUS
; i
++)
2186 if (radius
[i
].state
== RADIUSNULL
)
2188 if (radius
[i
].state
== RADIUSWAIT
)
2191 if (last_talked
!= TIME
)
2193 log(2,0,0,0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2202 static fd_set readset
;
2203 static int readset_n
= 0;
2205 // main loop - gets packets on tun or udp and processes them
2211 clockt next_cluster_ping
= 0; // send initial ping immediately
2212 time_t next_clean
= time_now
+ config
->cleanup_interval
;
2214 log(4, 0, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2215 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2218 FD_SET(udpfd
, &readset
);
2219 FD_SET(tunfd
, &readset
);
2220 FD_SET(controlfd
, &readset
);
2221 FD_SET(clifd
, &readset
);
2222 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2224 if (tunfd
> readset_n
) readset_n
= tunfd
;
2225 if (controlfd
> readset_n
) readset_n
= controlfd
;
2226 if (clifd
> readset_n
) readset_n
= clifd
;
2227 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2229 while (!main_quit
|| still_busy())
2235 int bgp_set
[BGP_NUM_PEERS
];
2238 if (config
->reload_config
)
2240 // Update the config state based on config settings
2244 memcpy(&r
, &readset
, sizeof(fd_set
));
2246 to
.tv_usec
= 100000; // 1/10th of a second.
2250 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2252 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2255 FD_SET(bgp_peers
[i
].sock
, &r
);
2256 if (bgp_peers
[i
].sock
> n
)
2257 n
= bgp_peers
[i
].sock
;
2262 FD_SET(bgp_peers
[i
].sock
, &w
);
2263 if (bgp_peers
[i
].sock
> n
)
2264 n
= bgp_peers
[i
].sock
;
2268 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2270 n
= select(n
+ 1, &r
, 0, 0, &to
);
2276 if (errno
== EINTR
||
2277 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2280 log(0, 0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2286 struct sockaddr_in addr
;
2287 int alen
= sizeof(addr
);
2288 if (FD_ISSET(udpfd
, &r
))
2291 for (c
= 0; c
< config
->multi_read_count
; c
++)
2293 if ((n
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
2294 processudp(buf
, n
, &addr
);
2299 if (FD_ISSET(tunfd
, &r
))
2302 for (c
= 0; c
< config
->multi_read_count
; c
++)
2304 if ((n
= read(tunfd
, buf
, sizeof(buf
))) > 0)
2311 if (config
->cluster_iam_master
)
2312 for (i
= 0; i
< config
->num_radfds
; i
++)
2313 if (FD_ISSET(radfds
[i
], &r
))
2314 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2316 if (FD_ISSET(cluster_sockfd
, &r
))
2319 size
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
);
2320 processcluster(buf
, size
, addr
.sin_addr
.s_addr
);
2323 if (FD_ISSET(controlfd
, &r
))
2324 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
);
2326 if (FD_ISSET(clifd
, &r
))
2328 struct sockaddr_in addr
;
2330 int len
= sizeof(addr
);
2332 if ((sockfd
= accept(clifd
, (struct sockaddr
*)&addr
, &len
)) <= 0)
2334 log(0, 0, 0, 0, "accept error: %s\n", strerror(errno
));
2345 // Runs on every machine (master and slaves).
2346 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
2348 // Check to see which of the cluster is still alive..
2350 cluster_send_ping(basetime
); // Only does anything if we're a slave
2351 cluster_check_master(); // ditto.
2353 cluster_heartbeat(); // Only does anything if we're a master.
2354 cluster_check_slaves(); // ditto.
2356 master_update_counts(); // If we're a slave, send our byte counters to our master.
2358 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
2359 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
2361 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
2364 // Run token bucket filtering queue..
2365 // Only run it every 1/10th of a second.
2366 // Runs on all machines both master and slave.
2368 static clockt last_run
= 0;
2369 if (last_run
!= TIME
)
2376 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2377 * something to read, else under load this will never actually run....
2380 if (config
->cluster_iam_master
&& next_clean
<= time_now
)
2382 if (regular_cleanups())
2385 next_clean
= time_now
+ 1 ; // Didn't finish. Check quickly.
2389 next_clean
= time_now
+ config
->cleanup_interval
; // Did. Move to next interval.
2394 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2396 bgp_process(&bgp_peers
[i
],
2397 bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0,
2398 bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0);
2403 // Are we the master and shutting down??
2404 if (config
->cluster_iam_master
)
2405 cluster_heartbeat(); // Flush any queued changes..
2407 // Ok. Notify everyone we're shutting down. If we're
2408 // the master, this will force an election.
2409 cluster_send_ping(0);
2412 // Important!!! We MUST not process any packets past this point!
2415 static void stripdomain(char *host
)
2419 if ((p
= strchr(host
, '.')))
2425 FILE *resolv
= fopen("/etc/resolv.conf", "r");
2431 while (fgets(buf
, sizeof(buf
), resolv
))
2433 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
2436 if (!isspace(buf
[6]))
2440 while (isspace(*b
)) b
++;
2445 while (*b
&& !isspace(*b
)) b
++;
2447 if (buf
[0] == 'd') // domain is canonical
2453 // first search line
2456 // hold, may be subsequent domain line
2457 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
2468 int hl
= strlen(host
);
2469 int dl
= strlen(domain
);
2470 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
2471 host
[hl
-dl
- 1] = 0;
2475 *p
= 0; // everything after first dot
2480 // Init data structures
2481 void initdata(int optdebug
, char *optconfig
)
2485 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
2487 log(0, 0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
2490 if (!(config
= shared_malloc(sizeof(struct configt
))))
2492 log(0, 0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2495 memset(config
, 0, sizeof(struct configt
));
2496 time(&config
->start_time
);
2497 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
2498 config
->debug
= optdebug
;
2499 config
->num_tbfs
= MAXTBFS
;
2500 config
->rl_rate
= 28; // 28kbps
2502 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
2504 log(0, 0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
2507 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
2509 log(0, 0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
2513 if (!(sess_count
= shared_malloc(sizeof(sessioncountt
) * MAXSESSION
)))
2515 log(0, 0, 0, 0, "Error doing malloc for sessions_count: %s\n", strerror(errno
));
2519 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
2521 log(0, 0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
2525 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
2527 log(0, 0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
2532 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2534 log(0, 0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2537 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2540 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2542 log(0, 0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2545 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2547 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2549 log(0, 0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2552 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2554 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2555 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2556 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2557 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2559 // Put all the sessions on the free list marked as undefined.
2560 for (i
= 1; i
< MAXSESSION
- 1; i
++)
2562 session
[i
].next
= i
+ 1;
2563 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2565 session
[MAXSESSION
- 1].next
= 0;
2568 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2569 for (i
= 1; i
< MAXTUNNEL
- 1; i
++)
2570 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2574 // Grab my hostname unless it's been specified
2575 gethostname(hostname
, sizeof(hostname
));
2576 stripdomain(hostname
);
2579 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2582 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2584 log(0, 0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2590 void initiptables(void)
2592 /* Flush the tables here so that we have a clean slate */
2594 // Not needed. 'nat' is setup by garden.c
2595 // mangle isn't used (as throttling is done by tbf inhouse).
2598 int assign_ip_address(sessionidt s
)
2602 time_t best_time
= time_now
;
2603 char *u
= session
[s
].user
;
2607 CSTAT(call_assign_ip_address
);
2609 for (i
= 1; i
< ip_pool_size
; i
++)
2611 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2614 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2621 if (ip_address_pool
[i
].last
< best_time
)
2624 if (!(best_time
= ip_address_pool
[i
].last
))
2625 break; // never used, grab this one
2631 log(0, 0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2635 session
[s
].ip
= ip_address_pool
[best
].address
;
2636 session
[s
].ip_pool_index
= best
;
2637 ip_address_pool
[best
].assigned
= 1;
2638 ip_address_pool
[best
].last
= time_now
;
2639 ip_address_pool
[best
].session
= s
;
2640 if (session
[s
].walled_garden
)
2641 /* Don't track addresses of users in walled garden (note: this
2642 means that their address isn't "sticky" even if they get
2644 ip_address_pool
[best
].user
[0] = 0;
2646 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2649 log(4, ip_address_pool
[best
].address
, s
, session
[s
].tunnel
,
2650 "assign_ip_address(): %s ip address %d from pool\n", reuse
? "Reusing" : "Allocating", best
);
2655 void free_ip_address(sessionidt s
)
2657 int i
= session
[s
].ip_pool_index
;
2660 return; // what the?
2662 if (i
< 0) // Is this actually part of the ip pool?
2666 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2668 ip_address_pool
[i
].assigned
= 0;
2669 ip_address_pool
[i
].session
= 0;
2670 ip_address_pool
[i
].last
= time_now
;
2673 CSTAT(call_free_ip_address
);
2678 // Fsck the address pool against the session table.
2679 // Normally only called when we become a master.
2681 // This isn't perfect: We aren't keep tracking of which
2682 // users used to have an IP address.
2684 void rebuild_address_pool(void)
2689 // Zero the IP pool allocation, and build
2690 // a map from IP address to pool index.
2691 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2693 ip_address_pool
[i
].assigned
= 0;
2694 ip_address_pool
[i
].session
= 0;
2695 if (!ip_address_pool
[i
].address
)
2698 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2701 for (i
= 0; i
< MAXSESSION
; ++i
)
2704 if (!session
[i
].ip
|| !session
[i
].tunnel
)
2706 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2708 if (session
[i
].ip_pool_index
< 0)
2710 // Not allocated out of the pool.
2711 if (ipid
< 1) // Not found in the pool either? good.
2714 log(0, 0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2715 i
, inet_toa(session
[i
].ip
), ipid
);
2717 // Fall through and process it as part of the pool.
2721 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2723 log(0, 0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2725 session
[i
].ip_pool_index
= ipid
;
2729 ip_address_pool
[ipid
].assigned
= 1;
2730 ip_address_pool
[ipid
].session
= i
;
2731 ip_address_pool
[ipid
].last
= time_now
;
2732 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2733 session
[i
].ip_pool_index
= ipid
;
2734 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
2739 // Fix the address pool to match a changed session.
2740 // (usually when the master sends us an update).
2741 void fix_address_pool(int sid
)
2745 ipid
= session
[sid
].ip_pool_index
;
2747 if (ipid
> ip_pool_size
)
2748 return; // Ignore it. rebuild_address_pool will fix it up.
2750 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
2751 return; // Just ignore it. rebuild_address_pool will take care of it.
2753 ip_address_pool
[ipid
].assigned
= 1;
2754 ip_address_pool
[ipid
].session
= sid
;
2755 ip_address_pool
[ipid
].last
= time_now
;
2756 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2760 // Add a block of addresses to the IP pool to hand out.
2762 void add_to_ip_pool(u32 addr
, u32 mask
)
2766 mask
= 0xffffffff; // Host route only.
2770 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
2773 for (i
= addr
;(i
& mask
) == addr
; ++i
)
2775 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
2776 continue; // Skip 0 and broadcast addresses.
2778 ip_address_pool
[ip_pool_size
].address
= i
;
2779 ip_address_pool
[ip_pool_size
].assigned
= 0;
2781 if (ip_pool_size
>= MAXIPPOOL
)
2783 log(0,0,0,0, "Overflowed IP pool adding %s\n", inet_toa(htonl(addr
)) );
2789 // Initialize the IP address pool
2795 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2797 if (!(f
= fopen(IPPOOLFILE
, "r")))
2799 log(0, 0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2803 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2806 buf
[4095] = 0; // Force it to be zero terminated/
2808 if (*buf
== '#' || *buf
== '\n')
2809 continue; // Skip comments / blank lines
2810 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2811 if ((p
= (char *)strchr(buf
, ':')))
2815 src
= inet_addr(buf
);
2816 if (src
== INADDR_NONE
)
2818 log(0, 0, 0, 0, "Invalid address pool IP %s\n", buf
);
2821 // This entry is for a specific IP only
2822 if (src
!= config
->bind_address
)
2827 if ((p
= (char *)strchr(pool
, '/')))
2831 u32 start
= 0, mask
= 0;
2833 log(2, 0, 0, 0, "Adding IP address range %s\n", buf
);
2835 if (!*p
|| !(numbits
= atoi(p
)))
2837 log(0, 0, 0, 0, "Invalid pool range %s\n", buf
);
2840 start
= ntohl(inet_addr(pool
));
2841 mask
= (u32
)(pow(2, numbits
) - 1) << (32 - numbits
);
2843 // Add a static route for this pool
2844 log(5, 0, 0, 0, "Adding route for address pool %s/%u\n", inet_toa(htonl(start
)), 32 + mask
);
2845 routeset(0, start
, mask
, 0, 1);
2847 add_to_ip_pool(start
, mask
);
2851 // It's a single ip address
2852 add_to_ip_pool(inet_addr(pool
), 0);
2856 log(1, 0, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
2859 void snoop_send_packet(char *packet
, u16 size
, ipt destination
, u16 port
)
2861 struct sockaddr_in snoop_addr
= {0};
2862 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2865 snoop_addr
.sin_family
= AF_INET
;
2866 snoop_addr
.sin_addr
.s_addr
= destination
;
2867 snoop_addr
.sin_port
= ntohs(port
);
2869 log(5, 0, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n",
2870 packet
, size
, inet_toa(snoop_addr
.sin_addr
.s_addr
), htons(snoop_addr
.sin_port
));
2871 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
2872 log(0, 0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
2873 STAT(packets_snooped
);
2876 void dump_acct_info()
2878 char filename
[1024];
2880 time_t t
= time(NULL
);
2885 CSTAT(call_dump_acct_info
);
2887 strftime(timestr
, 64, "%Y%m%d%H%M%S", localtime(&t
));
2888 snprintf(filename
, 1024, "%s/%s", config
->accounting_dir
, timestr
);
2890 for (i
= 0; i
< MAXSESSION
; i
++)
2892 if (!session
[i
].opened
|| !session
[i
].ip
|| !(session
[i
].cin
|| session
[i
].cout
) || !*session
[i
].user
|| session
[i
].walled_garden
)
2896 time_t now
= time(NULL
);
2897 if (!(f
= fopen(filename
, "w")))
2899 log(0, 0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
2902 log(3, 0, 0, 0, "Dumping accounting information to %s\n", filename
);
2903 fprintf(f
, "# dslwatch.pl dump file V1.01\n"
2907 "# format: username ip qos uptxoctets downrxoctets\n",
2913 log(4, 0, 0, 0, "Dumping accounting information for %s\n", session
[i
].user
);
2914 fprintf(f
, "%s %s %d %u %u\n",
2915 session
[i
].user
, // username
2916 inet_toa(htonl(session
[i
].ip
)), // ip
2917 (session
[i
].throttle_in
|| session
[i
].throttle_out
) ? 2 : 1, // qos
2918 (u32
)session
[i
].cin
, // uptxoctets
2919 (u32
)session
[i
].cout
); // downrxoctets
2921 session
[i
].pin
= session
[i
].cin
= 0;
2922 session
[i
].pout
= session
[i
].cout
= 0;
2930 int main(int argc
, char *argv
[])
2934 char *optconfig
= CONFIGFILE
;
2936 _program_name
= strdup(argv
[0]);
2938 time(&basetime
); // start clock
2941 while ((o
= getopt(argc
, argv
, "dvc:h:")) >= 0)
2946 // Double fork to detach from terminal
2947 if (fork()) exit(0);
2948 if (fork()) exit(0);
2957 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
2960 printf("Args are:\n"
2961 "\t-d\tDetach from terminal\n"
2962 "\t-c <file>\tConfig file\n"
2963 "\t-h <hostname>\tForce hostname\n"
2964 "\t-a <address>\tUse specific address\n"
2972 // Start the timer routine off
2974 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
2975 signal(SIGALRM
, sigalrm_handler
);
2976 siginterrupt(SIGALRM
, 0);
2980 initdata(optdebug
, optconfig
);
2984 init_tbf(config
->num_tbfs
);
2986 log(0, 0, 0, 0, "L2TPNS version " VERSION
"\n");
2987 log(0, 0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
2988 log(0, 0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
2991 rlim
.rlim_cur
= RLIM_INFINITY
;
2992 rlim
.rlim_max
= RLIM_INFINITY
;
2993 // Remove the maximum core size
2994 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
2995 log(0, 0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
2996 // Make core dumps go to /tmp
3000 if (config
->scheduler_fifo
)
3003 struct sched_param params
= {0};
3004 params
.sched_priority
= 1;
3006 if (get_nprocs() < 2)
3008 log(0, 0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3009 config
->scheduler_fifo
= 0;
3013 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3015 log(1, 0, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3019 log(0, 0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3020 config
->scheduler_fifo
= 0;
3025 /* Set up the cluster communications port. */
3026 if (cluster_init(config
->bind_address
) < 0)
3030 signal(SIGPIPE
, SIG_IGN
);
3031 bgp_setup(config
->as_number
);
3032 bgp_add_route(config
->bind_address
, 0xffffffff);
3033 if (*config
->bgp_peer
[0])
3034 bgp_start(&bgp_peers
[0], config
->bgp_peer
[0],
3035 config
->bgp_peer_as
[0], 0); /* 0 = routing disabled */
3037 if (*config
->bgp_peer
[1])
3038 bgp_start(&bgp_peers
[1], config
->bgp_peer
[1],
3039 config
->bgp_peer_as
[1], 0);
3043 log(1, 0, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3051 signal(SIGHUP
, sighup_handler
);
3052 signal(SIGTERM
, sigterm_handler
);
3053 signal(SIGINT
, sigterm_handler
);
3054 signal(SIGQUIT
, sigquit_handler
);
3055 signal(SIGCHLD
, sigchild_handler
);
3057 // Prevent us from getting paged out
3058 if (config
->lock_pages
)
3060 if (!mlockall(MCL_CURRENT
))
3061 log(1, 0, 0, 0, "Locking pages into memory\n");
3063 log(0, 0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3068 // Drop privileges here
3069 if (config
->target_uid
> 0 && geteuid() == 0)
3070 setuid(config
->target_uid
);
3075 /* try to shut BGP down cleanly; with luck the sockets will be
3076 writable since we're out of the select */
3079 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3080 if (bgp_peers
[i
].state
== Established
)
3081 bgp_stop(&bgp_peers
[i
]);
3085 /* remove plugins (so cleanup code gets run) */
3088 // Remove the PID file if we wrote it
3089 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3090 unlink(config
->pid_file
);
3092 /* kill CLI children */
3093 signal(SIGTERM
, SIG_IGN
);
3098 void sighup_handler(int junk
)
3100 if (log_stream
&& log_stream
!= stderr
)
3109 void sigalrm_handler(int junk
)
3111 // Log current traffic stats
3113 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3114 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3115 (udp_rx
/ 1024.0 / 1024.0 * 8),
3116 (eth_tx
/ 1024.0 / 1024.0 * 8),
3117 (eth_rx
/ 1024.0 / 1024.0 * 8),
3118 (udp_tx
/ 1024.0 / 1024.0 * 8),
3119 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3120 udp_rx_pkt
, eth_rx_pkt
);
3122 udp_tx
= udp_rx
= 0;
3123 udp_rx_pkt
= eth_rx_pkt
= 0;
3124 eth_tx
= eth_rx
= 0;
3126 if (config
->dump_speed
)
3127 printf("%s\n", config
->bandwidth
);
3129 // Update the internal time counter
3131 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3136 struct param_timer p
= { time_now
};
3137 run_plugins(PLUGIN_TIMER
, &p
);
3142 void sigterm_handler(int junk
)
3144 log(1, 0, 0, 0, "Shutting down cleanly\n");
3145 if (config
->save_state
)
3151 void sigquit_handler(int junk
)
3155 log(1, 0, 0, 0, "Shutting down without saving sessions\n");
3156 for (i
= 1; i
< MAXSESSION
; i
++)
3158 if (session
[i
].opened
)
3159 sessionkill(i
, "L2TPNS Closing");
3161 for (i
= 1; i
< MAXTUNNEL
; i
++)
3163 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3164 tunnelshutdown(i
, "L2TPNS Closing");
3170 void sigchild_handler(int signal
)
3172 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3182 char magic
[sizeof(DUMP_MAGIC
) - 1];
3185 if (!config
->save_state
)
3191 if (stat(STATEFILE
, &sb
) < 0)
3197 if (sb
.st_mtime
< (time(NULL
) - 60))
3199 log(0, 0, 0, 0, "State file is too old to read, ignoring\n");
3204 f
= fopen(STATEFILE
, "r");
3209 log(0, 0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3213 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3215 log(0, 0, 0, 0, "Bad state file magic\n");
3219 log(1, 0, 0, 0, "Reading state information\n");
3220 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3222 log(0, 0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3226 if (buf
[0] > ip_pool_size
)
3228 log(0, 0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3232 log(2, 0, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3233 for (i
= 0; i
< buf
[0]; i
++)
3235 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3237 log(0, 0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3241 if (itmp
.address
!= ip_address_pool
[i
].address
)
3243 log(0, 0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3247 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3250 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3252 log(0, 0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3256 log(2, 0, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3257 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3259 log(0, 0, 0, 0, "Error reading tunnel data from state file\n");
3263 for (i
= 0; i
< MAXTUNNEL
; i
++)
3265 tunnel
[i
].controlc
= 0;
3266 tunnel
[i
].controls
= NULL
;
3267 tunnel
[i
].controle
= NULL
;
3268 if (*tunnel
[i
].hostname
)
3269 log(3, 0, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3272 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3274 log(0, 0, 0, 0, "Error/mismatch reading session header from state file\n");
3278 log(2, 0, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3279 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3281 log(0, 0, 0, 0, "Error reading session data from state file\n");
3285 for (i
= 0; i
< MAXSESSION
; i
++)
3287 session
[i
].tbf_in
= 0;
3288 session
[i
].tbf_out
= 0;
3289 if (session
[i
].opened
)
3291 log(2, 0, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3293 sessionsetup(session
[i
].tunnel
, i
);
3298 log(0, 0, 0, 0, "Loaded saved state information\n");
3306 if (!config
->save_state
)
3311 if (!(f
= fopen(STATEFILE
, "w")))
3314 log(1, 0, 0, 0, "Dumping state information\n");
3316 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3319 log(2, 0, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3320 buf
[0] = ip_pool_size
;
3321 buf
[1] = sizeof(ippoolt
);
3322 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3324 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3327 log(2, 0, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3329 buf
[1] = sizeof(tunnelt
);
3330 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3332 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3335 log(2, 0, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3336 buf
[0] = MAXSESSION
;
3337 buf
[1] = sizeof(sessiont
);
3338 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3340 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3348 log(0, 0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3352 void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
)
3355 *challenge_response
= NULL
;
3357 if (!*config
->l2tpsecret
)
3359 log(0, 0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3363 log(4, 0, 0, 0, " Building challenge response for CHAP request\n");
3365 *challenge_response
= (char *)calloc(17, 1);
3368 MD5Update(&ctx
, &id
, 1);
3369 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3370 MD5Update(&ctx
, challenge
, challenge_length
);
3371 MD5Final(*challenge_response
, &ctx
);
3376 static int facility_value(char *name
)
3379 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3381 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3382 return facilitynames
[i
].c_val
;
3387 void update_config()
3390 static int timeout
= 0;
3391 static int interval
= 0;
3401 if (*config
->log_filename
)
3403 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3405 char *p
= config
->log_filename
+ 7;
3408 openlog("l2tpns", LOG_PID
, facility_value(p
));
3412 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3414 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3416 fseek(log_stream
, 0, SEEK_END
);
3417 setbuf(log_stream
, NULL
);
3421 log_stream
= stderr
;
3422 setbuf(log_stream
, NULL
);
3428 log_stream
= stderr
;
3429 setbuf(log_stream
, NULL
);
3434 config
->numradiusservers
= 0;
3435 for (i
= 0; i
< MAXRADSERVER
; i
++)
3436 if (config
->radiusserver
[i
])
3438 config
->numradiusservers
++;
3439 // Set radius port: if not set, take the port from the
3440 // first radius server. For the first radius server,
3441 // take the #defined default value from l2tpns.h
3443 // test twice, In case someone works with
3444 // a secondary radius server without defining
3445 // a primary one, this will work even then.
3446 if (i
>0 && !config
->radiusport
[i
])
3447 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3448 if (!config
->radiusport
[i
])
3449 config
->radiusport
[i
] = RADPORT
;
3452 if (!config
->numradiusservers
)
3454 log(0, 0, 0, 0, "No RADIUS servers defined!\n");
3457 config
->num_radfds
= 2 << RADIUS_SHIFT
;
3460 for (i
= 0; i
< MAXPLUGINS
; i
++)
3462 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3464 if (*config
->plugins
[i
])
3467 add_plugin(config
->plugins
[i
]);
3469 else if (*config
->old_plugins
[i
])
3472 remove_plugin(config
->old_plugins
[i
]);
3475 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3476 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
3477 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3478 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3479 if (!*config
->cluster_interface
)
3480 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3482 if (!config
->cluster_hb_interval
)
3483 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3485 if (!config
->cluster_hb_timeout
)
3486 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3488 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3490 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3491 // late, ensure we're sufficiently larger than that
3492 int t
= 4 * config
->cluster_hb_interval
+ 11;
3494 if (config
->cluster_hb_timeout
< t
)
3496 log(0,0,0,0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3497 config
->cluster_hb_timeout
= t
;
3500 // Push timing changes to the slaves immediately if we're the master
3501 if (config
->cluster_iam_master
)
3502 cluster_heartbeat();
3504 interval
= config
->cluster_hb_interval
;
3505 timeout
= config
->cluster_hb_timeout
;
3509 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3512 if ((f
= fopen(config
->pid_file
, "w")))
3514 fprintf(f
, "%d\n", getpid());
3516 config
->wrote_pid
= 1;
3520 log(0, 0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3524 config
->reload_config
= 0;
3527 void read_config_file()
3531 if (!config
->config_file
) return;
3532 if (!(f
= fopen(config
->config_file
, "r")))
3534 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3538 log(3, 0, 0, 0, "Reading config file %s\n", config
->config_file
);
3540 log(3, 0, 0, 0, "Done reading config file\n");
3545 int sessionsetup(tunnelidt t
, sessionidt s
)
3547 // A session now exists, set it up
3553 CSTAT(call_sessionsetup
);
3555 log(3, session
[s
].ip
, s
, t
, "Doing session setup for session\n");
3557 if (!session
[s
].ip
|| session
[s
].ip
== 0xFFFFFFFE)
3559 assign_ip_address(s
);
3562 log(0, 0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3563 sessionshutdown(s
, "No IP addresses available");
3566 log(3, 0, s
, t
, " No IP allocated. Assigned %s from pool\n",
3567 inet_toa(htonl(session
[s
].ip
)));
3571 // Make sure this is right
3572 session
[s
].tunnel
= t
;
3574 // zap old sessions with same IP and/or username
3575 // Don't kill gardened sessions - doing so leads to a DoS
3576 // from someone who doesn't need to know the password
3579 user
= session
[s
].user
;
3580 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3582 if (i
== s
) continue;
3583 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3584 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3585 sessionkill(i
, "Duplicate session for users");
3589 // Add the route for this session.
3591 // Static IPs need to be routed. Anything else
3592 // is part of the IP address pool and is already routed,
3593 // it just needs to be added to the IP cache.
3594 if (session
[s
].ip_pool_index
== -1) // static ip
3595 routeset(s
, session
[s
].ip
, 0, 0, 1);
3597 cache_ipmap(session
[s
].ip
, s
);
3599 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3600 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, session
[s
].ip
, 1);
3602 if (!session
[s
].unique_id
)
3604 // did this session just finish radius?
3605 log(3, session
[s
].ip
, s
, t
, "Sending initial IPCP to client\n");
3607 session
[s
].unique_id
= ++last_id
;
3610 // Run the plugin's against this new session.
3612 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3613 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3616 // Allocate TBFs if throttled
3617 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3618 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3620 session
[s
].last_packet
= time_now
;
3623 char *sessionip
, *tunnelip
;
3624 sessionip
= strdup(inet_toa(htonl(session
[s
].ip
)));
3625 tunnelip
= strdup(inet_toa(htonl(tunnel
[t
].ip
)));
3626 log(2, session
[s
].ip
, s
, t
, "Login by %s at %s from %s (%s)\n",
3627 session
[s
].user
, sessionip
, tunnelip
, tunnel
[t
].hostname
);
3628 if (sessionip
) free(sessionip
);
3629 if (tunnelip
) free(tunnelip
);
3632 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3634 return 1; // RADIUS OK and IP allocated, done...
3638 // This session just got dropped on us by the master or something.
3639 // Make sure our tables up up to date...
3641 int load_session(sessionidt s
, sessiont
*new)
3646 if (new->ip_pool_index
>= MAXIPPOOL
||
3647 new->tunnel
>= MAXTUNNEL
)
3649 log(0,0,s
,0, "Strange session update received!\n");
3650 // FIXME! What to do here?
3655 // Ok. All sanity checks passed. Now we're committed to
3656 // loading the new session.
3659 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3662 if (new->ip
!= session
[s
].ip
) // Changed ip. fix up hash tables.
3664 if (session
[s
].ip
) // If there's an old one, remove it.
3666 // Remove any routes if the IP has changed
3667 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3669 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, session
[s
].ip
, 0);
3670 session
[s
].route
[i
].ip
= 0;
3673 if (session
[s
].ip_pool_index
== -1) // static IP
3674 routeset(s
, session
[s
].ip
, 0, 0, 0);
3675 else // It's part of the IP pool, remove it manually.
3676 uncache_ipmap(session
[s
].ip
);
3681 // If there's a new one, add it.
3682 if (new->ip_pool_index
== -1)
3683 routeset(s
, new->ip
, 0, 0, 1);
3685 cache_ipmap(new->ip
, s
);
3689 // Update routed networks
3690 for (i
= 0; i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3692 if (new->route
[i
].ip
== session
[s
].route
[i
].ip
&&
3693 new->route
[i
].mask
== session
[s
].route
[i
].mask
)
3696 if (session
[s
].route
[i
].ip
) // Remove the old one if it exists.
3697 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, session
[s
].ip
, 0);
3699 if (new->route
[i
].ip
) // Add the new one if it exists.
3700 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, new->ip
, 1);
3703 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
3704 // for walking the sessions to forward byte counts to the master.
3705 config
->cluster_highest_sessionid
= s
;
3707 // TEMP: old session struct used a u32 to define the throttle
3708 // speed for both up/down, new uses a u16 for each. Deal with
3709 // sessions from an old master for migration.
3710 if (new->throttle_out
== 0 && new->tbf_out
)
3711 new->throttle_out
= new->throttle_in
;
3713 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
3715 // Do fixups into address pool.
3716 if (new->ip_pool_index
!= -1)
3717 fix_address_pool(s
);
3723 void ringbuffer_dump(FILE *stream
)
3725 int i
= ringbuffer
->head
;
3727 while (i
!= ringbuffer
->tail
)
3729 if (*ringbuffer
->buffer
[i
].message
)
3730 fprintf(stream
, "%d-%s", ringbuffer
->buffer
[i
].level
, ringbuffer
->buffer
[i
].message
);
3731 if (++i
== ringbuffer
->tail
) break;
3732 if (i
== RINGBUFFER_SIZE
) i
= 0;
3741 loaded_plugins
= ll_init();
3742 // Initialize the plugins to nothing
3743 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
3744 plugins
[i
] = ll_init();
3747 static void *open_plugin(char *plugin_name
, int load
)
3749 char path
[256] = "";
3751 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
3752 log(2, 0, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
3753 return dlopen(path
, RTLD_NOW
);
3756 void add_plugin(char *plugin_name
)
3758 static struct pluginfuncs funcs
= {
3763 sessiontbysessionidt
,
3764 sessionidtbysessiont
,
3770 void *p
= open_plugin(plugin_name
, 1);
3771 int (*initfunc
)(struct pluginfuncs
*);
3776 log(1, 0, 0, 0, " Plugin load failed: %s\n", dlerror());
3780 if (ll_contains(loaded_plugins
, p
))
3787 int *v
= dlsym(p
, "__plugin_api_version");
3788 if (!v
|| *v
!= PLUGIN_API_VERSION
)
3790 log(1, 0, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
3796 if ((initfunc
= dlsym(p
, "plugin_init")))
3798 if (!initfunc(&funcs
))
3800 log(1, 0, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
3806 ll_push(loaded_plugins
, p
);
3808 for (i
= 0; i
< max_plugin_functions
; i
++)
3811 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3813 log(3, 0, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
3814 ll_push(plugins
[i
], x
);
3818 log(2, 0, 0, 0, " Loaded plugin %s\n", plugin_name
);
3821 static void run_plugin_done(void *plugin
)
3823 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
3829 void remove_plugin(char *plugin_name
)
3831 void *p
= open_plugin(plugin_name
, 0);
3837 for (i
= 0; i
< max_plugin_functions
; i
++)
3840 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3841 ll_delete(plugins
[i
], x
);
3844 if (ll_contains(loaded_plugins
, p
))
3846 ll_delete(loaded_plugins
, p
);
3851 log(2, 0, 0, 0, "Removed plugin %s\n", plugin_name
);
3854 int run_plugins(int plugin_type
, void *data
)
3856 int (*func
)(void *data
);
3857 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
) return 1;
3859 ll_reset(plugins
[plugin_type
]);
3860 while ((func
= ll_next(plugins
[plugin_type
])))
3864 if (rc
== PLUGIN_RET_STOP
) return 1;
3865 if (rc
== PLUGIN_RET_ERROR
) return 0;
3874 ll_reset(loaded_plugins
);
3875 while ((p
= ll_next(loaded_plugins
)))
3879 void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
)
3883 struct param_control param
= { buf
, len
, ntohl(addr
->sin_addr
.s_addr
), ntohs(addr
->sin_port
), NULL
, 0, 0 };
3886 if (log_stream
&& config
->debug
>= 4)
3888 log(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Received ");
3889 dump_packet(buf
, log_stream
);
3892 resp
= calloc(1400, 1);
3893 l
= new_packet(PKT_RESP_ERROR
, resp
);
3894 *(int *)(resp
+ 6) = *(int *)(buf
+ 6);
3896 param
.type
= ntohs(*(short *)(buf
+ 2));
3897 param
.id
= ntohl(*(int *)(buf
+ 6));
3898 param
.data_length
= ntohs(*(short *)(buf
+ 4)) - 10;
3899 param
.data
= (param
.data_length
> 0) ? (char *)(buf
+ 10) : NULL
;
3900 param
.response
= resp
;
3901 param
.response_length
= l
;
3903 run_plugins(PLUGIN_CONTROL
, ¶m
);
3905 if (param
.send_response
)
3907 send_packet(controlfd
, ntohl(addr
->sin_addr
.s_addr
), ntohs(addr
->sin_port
), param
.response
, param
.response_length
);
3908 log(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Sent Control packet response\n");
3916 * Go through all of the tunnels and do some cleanups
3922 log(1, 0, 0, 0, "Cleaning tunnels array\n");
3924 for (i
= 1; i
< MAXTUNNEL
; i
++)
3927 || !*tunnel
[i
].hostname
3928 || (tunnel
[i
].state
== TUNNELDIE
&& tunnel
[i
].die
>= time_now
))
3935 void tunnelclear(tunnelidt t
)
3938 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
3939 tunnel
[t
].state
= TUNNELFREE
;
3942 tunnelidt
new_tunnel()
3945 for (i
= 1; i
< MAXTUNNEL
; i
++)
3947 if (tunnel
[i
].state
== TUNNELFREE
)
3949 log(4, 0, 0, i
, "Assigning tunnel ID %d\n", i
);
3950 if (i
> config
->cluster_highest_tunnelid
)
3951 config
->cluster_highest_tunnelid
= i
;
3955 log(0, 0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
3960 // We're becoming the master. Do any required setup..
3962 // This is principally telling all the plugins that we're
3963 // now a master, and telling them about all the sessions
3964 // that are active too..
3966 void become_master(void)
3969 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
3971 // running a bunch of iptables commands is slow and can cause
3972 // the master to drop tunnels on takeover--kludge around the
3973 // problem by forking for the moment (note: race)
3974 if (!fork_and_close())
3976 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
3978 if (!session
[s
].tunnel
) // Not an in-use session.
3981 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
3987 for (i
= 0; i
< config
->num_radfds
; i
++)
3989 if (!radfds
[i
]) continue;
3990 FD_SET(radfds
[i
], &readset
);
3991 if (radfds
[i
] > readset_n
)
3992 readset_n
= radfds
[i
];
3996 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4002 if (CLI_HELP_REQUESTED
)
4003 return CLI_HELP_NO_ARGS
;
4006 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4008 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4011 if (!session
[s
].tunnel
)
4014 idle
= time_now
- session
[s
].last_packet
;
4015 idle
/= 5 ; // In multiples of 5 seconds.
4025 for (i
= 0; i
< 63; ++i
)
4027 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4029 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4030 cli_print(cli
, "%d total sessions open.", count
);
4034 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4040 if (CLI_HELP_REQUESTED
)
4041 return CLI_HELP_NO_ARGS
;
4044 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4046 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4049 if (!session
[s
].tunnel
)
4052 d
= time_now
- session
[s
].opened
;
4055 while (d
> 1 && open
< 32)
4065 for (i
= 0; i
< 30; ++i
)
4067 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4070 cli_print(cli
, "%d total sessions open.", count
);
4076 * This unencodes the AVP using the L2TP CHAP secret and the
4077 * previously stored random vector. It replaces the hidden data with
4078 * the cleartext data and returns the length of the cleartext data
4079 * (including the AVP "header" of 6 bytes).
4081 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4083 int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
)
4088 u8 working_vector
[16];
4089 uint16_t hidden_length
;
4094 // Find the AVP type.
4095 type
[0] = *(avp
+ 4);
4096 type
[1] = *(avp
+ 5);
4098 // Line up with the hidden data
4099 cursor
= output
= avp
+ 6;
4101 // Compute initial pad
4103 MD5Update(&ctx
, type
, 2);
4104 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4105 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4106 MD5Final(digest
, &ctx
);
4108 // Get hidden length
4109 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4111 // Keep these for later use
4112 working_vector
[0] = *cursor
;
4113 working_vector
[1] = *(cursor
+ 1);
4116 if (hidden_length
> length
- 8)
4118 log(1, 0, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4122 /* Decrypt remainder */
4124 todo
= hidden_length
;
4127 working_vector
[done
] = *cursor
;
4128 *output
= digest
[done
] ^ *cursor
;
4133 if (done
== 16 && todo
)
4135 // Compute new digest
4138 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4139 MD5Update(&ctx
, &working_vector
, 16);
4140 MD5Final(digest
, &ctx
);
4144 return hidden_length
+ 6;