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.45 2004/11/05 07:50:05 bodea Exp $";
13 #include <linux/if_tun.h>
18 #include <net/route.h>
21 #include <netinet/in.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
31 #include <sys/resource.h>
39 #include <sys/sysinfo.h>
47 #include "constants.h"
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("peer_address", peer_address
, IP
),
111 CONFIG("send_garp", send_garp
, BOOL
),
112 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
113 CONFIG("throttle_buckets", num_tbfs
, INT
),
114 CONFIG("accounting_dir", accounting_dir
, STRING
),
115 CONFIG("setuid", target_uid
, INT
),
116 CONFIG("dump_speed", dump_speed
, BOOL
),
117 CONFIG("cleanup_interval", cleanup_interval
, INT
),
118 CONFIG("multi_read_count", multi_read_count
, INT
),
119 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
120 CONFIG("lock_pages", lock_pages
, BOOL
),
121 CONFIG("icmp_rate", icmp_rate
, INT
),
122 CONFIG("cluster_address", cluster_address
, IP
),
123 CONFIG("cluster_interface", cluster_interface
, STRING
),
124 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
125 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
127 CONFIG("as_number", as_number
, SHORT
),
128 CONFIG("bgp_peer1", bgp_peer
[0], STRING
),
129 CONFIG("bgp_peer1_as", bgp_peer_as
[0], SHORT
),
130 CONFIG("bgp_peer2", bgp_peer
[1], STRING
),
131 CONFIG("bgp_peer2_as", bgp_peer_as
[1], SHORT
),
136 char *plugin_functions
[] = {
143 "plugin_new_session",
144 "plugin_kill_session",
146 "plugin_radius_response",
147 "plugin_become_master",
148 "plugin_new_session_master",
151 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
153 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
154 sessiont
*session
= NULL
; // Array of session structures.
155 sessioncountt
*sess_count
= NULL
; // Array of partial per-session traffic counters.
156 radiust
*radius
= NULL
; // Array of radius structures.
157 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
158 controlt
*controlfree
= 0;
159 struct Tstats
*_statistics
= NULL
;
161 struct Tringbuffer
*ringbuffer
= NULL
;
164 void sigalrm_handler(int);
165 void sighup_handler(int);
166 void sigterm_handler(int);
167 void sigquit_handler(int);
168 void sigchild_handler(int);
169 void read_config_file();
173 tunnelidt
new_tunnel();
174 void update_config();
175 int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
);
177 static void cache_ipmap(ipt ip
, int s
);
178 static void uncache_ipmap(ipt ip
);
180 // return internal time (10ths since process startup)
185 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
188 // work out a retry time based on try number
189 // This is a straight bounded exponential backoff.
190 // Maximum re-try time is 32 seconds. (2^5).
191 clockt
backoff(u8
try)
193 if (try > 5) try = 5; // max backoff
194 return now() + 10 * (1 << try);
199 // Log a debug message. Typically called vias LOG macro
201 void _log(int level
, ipt address
, sessionidt s
, tunnelidt t
, const char *format
, ...)
203 static char message
[65536] = {0};
204 static char message2
[65536] = {0};
210 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
211 ringbuffer
->tail
= 0;
212 if (ringbuffer
->tail
== ringbuffer
->head
)
213 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
214 ringbuffer
->head
= 0;
216 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
217 ringbuffer
->buffer
[ringbuffer
->tail
].address
= address
;
218 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
219 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
220 va_start(ap
, format
);
221 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
226 if (config
->debug
< level
) return;
228 va_start(ap
, format
);
231 vsnprintf(message2
, 65535, format
, ap
);
232 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
233 fprintf(log_stream
, "%s", message
);
237 vsnprintf(message2
, 65535, format
, ap
);
238 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
239 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
244 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
247 const u8
*d
= (const u8
*)data
;
249 if (config
->debug
< level
) return;
251 // No support for _log_hex to syslog
254 _log(level
, 0, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
255 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
257 for (i
= 0; i
< maxsize
; )
259 fprintf(log_stream
, "%4X: ", i
);
260 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
262 fprintf(log_stream
, "%02X ", d
[j
]);
264 fputs(": ", log_stream
);
267 for (; j
< i
+ 16; j
++)
269 fputs(" ", log_stream
);
271 fputs(": ", log_stream
);
274 fputs(" ", log_stream
);
275 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
277 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
278 fputc(d
[j
], log_stream
);
280 fputc('.', log_stream
);
283 fputs(" ", log_stream
);
287 fputs("\n", log_stream
);
291 setbuf(log_stream
, NULL
);
298 // This adds it to the routing table, advertises it
299 // via iBGP if enabled, and stuffs it into the
300 // 'sessionbyip' cache.
302 // 'ip' and 'mask' must be in _host_ order.
304 void routeset(sessionidt s
, ipt ip
, ipt mask
, ipt gw
, u8 add
)
309 if (!mask
) mask
= 0xffffffff;
311 ip
&= mask
; // Force the ip to be the first one in the route.
313 memset(&r
, 0, sizeof(r
));
314 r
.rt_dev
= config
->tundevice
;
315 r
.rt_dst
.sa_family
= AF_INET
;
316 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
317 r
.rt_gateway
.sa_family
= AF_INET
;
318 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
319 r
.rt_genmask
.sa_family
= AF_INET
;
320 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
321 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
323 r
.rt_flags
|= RTF_GATEWAY
;
324 else if (mask
== 0xffffffff)
325 r
.rt_flags
|= RTF_HOST
;
327 LOG(1, ip
, 0, 0, "Route %s %u.%u.%u.%u/%u.%u.%u.%u %u.%u.%u.%u\n",
329 ip
>> 24, ip
>> 16 & 0xff, ip
>> 8 & 0xff, ip
& 0xff,
330 mask
>> 24, mask
>> 16 & 0xff, mask
>> 8 & 0xff, mask
& 0xff,
331 gw
>> 24, gw
>> 16 & 0xff, gw
>> 8 & 0xff, gw
& 0xff);
333 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
334 LOG(0, 0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
338 bgp_add_route(htonl(ip
), htonl(mask
));
340 bgp_del_route(htonl(ip
), htonl(mask
));
343 // Add/Remove the IPs to the 'sessionbyip' cache.
344 // Note that we add the zero address in the case of
345 // a network route. Roll on CIDR.
347 // Note that 's == 0' implies this is the address pool.
348 // We still cache it here, because it will pre-fill
349 // the malloc'ed tree.
353 if (!add
) // Are we deleting a route?
354 s
= 0; // Caching the session as '0' is the same as uncaching.
356 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
362 // Set up TUN interface
366 struct sockaddr_in sin
= {0};
367 memset(&ifr
, 0, sizeof(ifr
));
368 ifr
.ifr_flags
= IFF_TUN
;
370 tunfd
= open(TUNDEVICE
, O_RDWR
);
373 LOG(0, 0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
377 int flags
= fcntl(tunfd
, F_GETFL
, 0);
378 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
380 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
382 LOG(0, 0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
385 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
386 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
387 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
389 sin
.sin_family
= AF_INET
;
390 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
391 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
393 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
395 LOG(0, 0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
398 /* Bump up the qlen to deal with bursts from the network */
400 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
402 LOG(0, 0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
405 ifr
.ifr_flags
= IFF_UP
;
406 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
408 LOG(0, 0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
411 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
413 LOG(0, 0, 0, 0, "Error setting tun ifindex: %s\n", strerror(errno
));
416 tunidx
= ifr
.ifr_ifindex
;
423 struct sockaddr_in addr
;
426 memset(&addr
, 0, sizeof(addr
));
427 addr
.sin_family
= AF_INET
;
428 addr
.sin_port
= htons(L2TPPORT
);
429 addr
.sin_addr
.s_addr
= config
->bind_address
;
430 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
431 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
433 int flags
= fcntl(udpfd
, F_GETFL
, 0);
434 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
436 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
438 LOG(0, 0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
441 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
444 memset(&addr
, 0, sizeof(addr
));
445 addr
.sin_family
= AF_INET
;
446 addr
.sin_port
= htons(1702);
447 controlfd
= socket(AF_INET
, SOCK_DGRAM
, 17);
448 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
449 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
451 LOG(0, 0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
457 // Find session by IP, < 1 for not found
459 // Confusingly enough, this 'ip' must be
460 // in _network_ order. This being the common
461 // case when looking it up from IP packet headers.
463 // We actually use this cache for two things.
464 // #1. For used IP addresses, this maps to the
465 // session ID that it's used by.
466 // #2. For un-used IP addresses, this maps to the
467 // index into the pool table that contains that
471 int lookup_ipmap(ipt ip
)
474 char **d
= (char **) ip_hash
;
477 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
478 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
479 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
481 s
= (ipt
) d
[(size_t) *a
];
485 sessionidt
sessionbyip(ipt ip
)
487 int s
= lookup_ipmap(ip
);
488 CSTAT(call_sessionbyip
);
490 if (s
> 0 && s
< MAXSESSION
&& session
[s
].tunnel
)
496 // Take an IP address in HOST byte order and
497 // add it to the sessionid by IP cache.
499 // (It's actually cached in network order)
501 static void cache_ipmap(ipt ip
, int s
)
503 ipt nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char*)(&ip))[0]
505 char **d
= (char **) ip_hash
;
508 for (i
= 0; i
< 3; i
++)
510 if (!d
[(size_t) a
[i
]])
512 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof (void *))))
516 d
= (char **) d
[(size_t) a
[i
]];
519 d
[(size_t) a
[3]] = (char *)((int)s
);
522 LOG(4, ip
, s
, session
[s
].tunnel
, "Caching ip address %s\n", inet_toa(nip
));
524 LOG(4, ip
, 0, 0, "Un-caching ip address %s\n", inet_toa(nip
));
525 // else a map to an ip pool index.
528 static void uncache_ipmap(ipt ip
)
530 cache_ipmap(ip
, 0); // Assign it to the NULL session.
534 // CLI list to dump current ipcache.
536 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
538 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
542 if (CLI_HELP_REQUESTED
)
543 return CLI_HELP_NO_ARGS
;
545 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
547 for (i
= 0; i
< 256; ++i
)
552 for (j
= 0; j
< 256; ++j
)
557 for (k
= 0; k
< 256; ++k
)
562 for (l
= 0; l
< 256; ++l
)
566 cli_print(cli
, "%7d %d.%d.%d.%d", (int) g
[l
], i
, j
, k
, l
);
572 cli_print(cli
, "%d entries in cache", count
);
577 // Find session by username, 0 for not found
578 // walled garden users aren't authenticated, so the username is
579 // reasonably useless. Ignore them to avoid incorrect actions
581 // This is VERY inefficent. Don't call it often. :)
583 sessionidt
sessionbyuser(char *username
)
586 CSTAT(call_sessionbyuser
);
588 for (s
= 1; s
< MAXSESSION
; ++s
)
590 if (session
[s
].walled_garden
)
591 continue; // Skip walled garden users.
593 if (!strncmp(session
[s
].user
, username
, 128))
597 return 0; // Not found.
600 void send_garp(ipt ip
)
606 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
609 LOG(0, 0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
612 memset(&ifr
, 0, sizeof(ifr
));
613 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
614 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
616 LOG(0, 0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
620 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
621 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
623 LOG(0, 0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
628 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
631 // Find session by username, 0 for not found
632 sessiont
*sessiontbysessionidt(sessionidt s
)
634 if (!s
|| s
> MAXSESSION
) return NULL
;
638 sessionidt
sessionidtbysessiont(sessiont
*s
)
640 sessionidt val
= s
-session
;
641 if (s
< session
|| val
> MAXSESSION
) return 0;
645 // actually send a control message for a specific tunnel
646 void tunnelsend(u8
* buf
, u16 l
, tunnelidt t
)
648 struct sockaddr_in addr
;
650 CSTAT(call_tunnelsend
);
654 static int backtrace_count
= 0;
655 LOG(0, 0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
656 STAT(tunnel_tx_errors
);
657 log_backtrace(backtrace_count
, 5)
663 static int backtrace_count
= 0;
664 LOG(1, 0, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
665 log_backtrace(backtrace_count
, 5)
666 STAT(tunnel_tx_errors
);
669 memset(&addr
, 0, sizeof(addr
));
670 addr
.sin_family
= AF_INET
;
671 *(u32
*) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
672 addr
.sin_port
= htons(tunnel
[t
].port
);
674 // sequence expected, if sequence in message
675 if (*buf
& 0x08) *(u16
*) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
677 // If this is a control message, deal with retries
680 tunnel
[t
].last
= time_now
; // control message sent
681 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
682 if (tunnel
[t
].try > 1)
684 STAT(tunnel_retries
);
685 LOG(3, tunnel
[t
].ip
, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
689 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
691 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",
692 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
693 STAT(tunnel_tx_errors
);
697 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
698 STAT(tunnel_tx_packets
);
699 INC_STAT(tunnel_tx_bytes
, l
);
703 // Tiny helper function to write data to
706 int tun_write(u8
* data
, int size
)
708 return write(tunfd
, data
, size
);
711 // process outgoing (to tunnel) IP
713 void processipout(u8
* buf
, int len
)
720 char * data
= buf
; // Keep a copy of the originals.
725 CSTAT(call_processipout
);
727 if (len
< MIN_IP_SIZE
)
729 LOG(1, 0, 0, 0, "Short IP, %d bytes\n", len
);
730 STAT(tunnel_tx_errors
);
735 LOG(1, 0, 0, 0, "Oversize IP packet %d bytes\n", len
);
736 STAT(tunnel_tx_errors
);
740 // Skip the tun header
744 // Got an IP header now
745 if (*(u8
*)(buf
) >> 4 != 4)
747 LOG(1, 0, 0, 0, "IP: Don't understand anything except IPv4\n");
751 ip
= *(u32
*)(buf
+ 16);
752 if (!(s
= sessionbyip(ip
)))
754 // Is this a packet for a session that doesn't exist?
755 static int rate
= 0; // Number of ICMP packets we've sent this second.
756 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
758 if (last
!= time_now
)
764 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
766 LOG(4, 0, 0, 0, "IP: Sending ICMP host unreachable to %s\n", inet_toa(*(u32
*)(buf
+ 12)));
767 host_unreachable(*(u32
*)(buf
+ 12), *(u16
*)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
771 t
= session
[s
].tunnel
;
776 // Are we throttling this session?
777 if (config
->cluster_iam_master
)
778 tbf_queue_packet(sp
->tbf_out
, data
, size
);
780 master_throttle_packet(sp
->tbf_out
, data
, size
);
783 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
785 // We are walled-gardening this
786 master_garden_packet(s
, data
, size
);
790 // Snooping this session, send it to intercept box
791 if (sp
->snoop_ip
&& sp
->snoop_port
)
792 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
794 LOG(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
796 // Add on L2TP header
798 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
801 LOG(3, session
[s
].ip
, s
, t
, "failed to send packet in processipout.\n");
804 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
807 sp
->cout
+= len
; // byte count
808 sp
->total_cout
+= len
; // byte count
811 sess_count
[s
].cout
+= len
; // To send to master..
815 // Helper routine for the TBF filters.
816 // Used to send queued data in to the user!
818 void send_ipout(sessionidt s
, u8
*buf
, int len
)
826 if (len
< 0 || len
> MAXETHER
)
828 LOG(1,0,0,0, "Odd size IP packet: %d bytes\n", len
);
832 // Skip the tun header
836 ip
= *(u32
*)(buf
+ 16);
840 t
= session
[s
].tunnel
;
843 LOG(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
845 // Snooping this session.
846 if (sp
->snoop_ip
&& sp
->snoop_port
)
847 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
849 // Add on L2TP header
851 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
854 LOG(3, session
[s
].ip
, s
, t
, "failed to send packet in send_ipout.\n");
857 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
859 sp
->cout
+= len
; // byte count
860 sp
->total_cout
+= len
; // byte count
863 sess_count
[s
].cout
+= len
; // To send to master..
866 // add an AVP (16 bit)
867 void control16(controlt
* c
, u16 avp
, u16 val
, u8 m
)
869 u16 l
= (m
? 0x8008 : 0x0008);
870 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
871 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
872 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
873 *(u16
*) (c
->buf
+ c
->length
+ 6) = htons(val
);
877 // add an AVP (32 bit)
878 void control32(controlt
* c
, u16 avp
, u32 val
, u8 m
)
880 u16 l
= (m
? 0x800A : 0x000A);
881 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
882 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
883 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
884 *(u32
*) (c
->buf
+ c
->length
+ 6) = htonl(val
);
888 // add an AVP (32 bit)
889 void controls(controlt
* c
, u16 avp
, char *val
, u8 m
)
891 u16 l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
892 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
893 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
894 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
895 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
896 c
->length
+= 6 + strlen(val
);
900 void controlb(controlt
* c
, u16 avp
, char *val
, unsigned int len
, u8 m
)
902 u16 l
= ((m
? 0x8000 : 0) + len
+ 6);
903 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
904 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
905 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
906 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
907 c
->length
+= 6 + len
;
910 // new control connection
911 controlt
*controlnew(u16 mtype
)
915 c
= malloc(sizeof(controlt
));
919 controlfree
= c
->next
;
923 *(u16
*) (c
->buf
+ 0) = htons(0xC802); // flags/ver
925 control16(c
, 0, mtype
, 1);
929 // send zero block if nothing is waiting
931 void controlnull(tunnelidt t
)
934 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
937 *(u16
*) (buf
+ 0) = htons(0xC802); // flags/ver
938 *(u16
*) (buf
+ 2) = htons(12); // length
939 *(u16
*) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
940 *(u16
*) (buf
+ 6) = htons(0); // session
941 *(u16
*) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
942 *(u16
*) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
943 tunnelsend(buf
, 12, t
);
946 // add a control message to a tunnel, and send if within window
947 void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
949 *(u16
*) (c
->buf
+ 2) = htons(c
->length
); // length
950 *(u16
*) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
951 *(u16
*) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
952 *(u16
*) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
953 tunnel
[t
].ns
++; // advance sequence
954 // link in message in to queue
955 if (tunnel
[t
].controlc
)
956 tunnel
[t
].controle
->next
= c
;
958 tunnel
[t
].controls
= c
;
959 tunnel
[t
].controle
= c
;
960 tunnel
[t
].controlc
++;
961 // send now if space in window
962 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
964 tunnel
[t
].try = 0; // first send
965 tunnelsend(c
->buf
, c
->length
, t
);
970 // Throttle or Unthrottle a session
972 // Throttle the data from/to through a session to no more than
973 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
976 // If either value is -1, the current value is retained for that
979 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
981 if (!session
[s
].tunnel
)
982 return; // No-one home.
984 if (!*session
[s
].user
)
985 return; // User not logged in
989 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
990 if (session
[s
].tbf_in
)
991 free_tbf(session
[s
].tbf_in
);
994 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
996 session
[s
].tbf_in
= 0;
998 session
[s
].throttle_in
= rate_in
;
1003 int bytes
= rate_out
* 1024 / 8;
1004 if (session
[s
].tbf_out
)
1005 free_tbf(session
[s
].tbf_out
);
1008 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1010 session
[s
].tbf_out
= 0;
1012 session
[s
].throttle_out
= rate_out
;
1016 // start tidy shutdown of session
1017 void sessionshutdown(sessionidt s
, char *reason
)
1019 int dead
= session
[s
].die
;
1020 int walled_garden
= session
[s
].walled_garden
;
1023 CSTAT(call_sessionshutdown
);
1025 if (!session
[s
].tunnel
)
1027 LOG(3, session
[s
].ip
, s
, session
[s
].tunnel
, "Called sessionshutdown on a session with no tunnel.\n");
1028 return; // not a live session
1032 LOG(2, 0, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1034 session
[s
].die
= now() + 150; // Clean up in 15 seconds
1037 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1038 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1041 // RADIUS Stop message
1042 if (session
[s
].opened
&& !walled_garden
&& !dead
)
1044 u16 r
= session
[s
].radius
;
1047 if (!(r
= radiusnew(s
)))
1049 LOG(1, 0, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1050 STAT(radius_overflow
);
1055 for (n
= 0; n
< 15; n
++)
1056 radius
[r
].auth
[n
] = rand();
1059 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1060 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1064 { // IP allocated, clear and unroute
1066 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1068 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, session
[s
].ip
, 0);
1069 session
[s
].route
[r
].ip
= 0;
1072 if (session
[s
].ip_pool_index
== -1) // static ip
1074 routeset(s
, session
[s
].ip
, 0, 0, 0); // Delete route.
1081 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1082 throttle_session(s
, 0, 0);
1085 controlt
*c
= controlnew(14); // sending CDN
1086 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1087 control16(c
, 14, s
, 1); // assigned session (our end)
1088 controladd(c
, session
[s
].tunnel
, s
); // send the message
1091 cluster_send_session(s
);
1094 void sendipcp(tunnelidt t
, sessionidt s
)
1097 u16 r
= session
[s
].radius
;
1100 CSTAT(call_sendipcp
);
1105 if (radius
[r
].state
!= RADIUSIPCP
)
1107 radius
[r
].state
= RADIUSIPCP
;
1111 radius
[r
].retry
= backoff(radius
[r
].try++);
1112 if (radius
[r
].try > 10)
1114 radiusclear(r
, s
); // Clear radius session.
1115 sessionshutdown(s
, "No reply on IPCP");
1119 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1122 LOG(3, session
[s
].ip
, s
, t
, "failed to send packet in sendipcp.\n");
1127 q
[1] = r
<< RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1128 *(u16
*) (q
+ 2) = htons(10);
1131 *(u32
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1132 config
->bind_address
? config
->bind_address
:
1133 my_address
; // send my IP
1135 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1136 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1139 // kill a session now
1140 void sessionkill(sessionidt s
, char *reason
)
1143 CSTAT(call_sessionkill
);
1145 session
[s
].die
= now();
1146 sessionshutdown(s
, reason
); // close radius/routes, etc.
1147 if (session
[s
].radius
)
1148 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1150 LOG(2, 0, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1152 memset(&session
[s
], 0, sizeof(session
[s
]));
1153 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1154 session
[s
].next
= sessionfree
;
1156 cli_session_actions
[s
].action
= 0;
1157 cluster_send_session(s
);
1160 // kill a tunnel now
1161 void tunnelkill(tunnelidt t
, char *reason
)
1166 CSTAT(call_tunnelkill
);
1168 tunnel
[t
].state
= TUNNELDIE
;
1170 // free control messages
1171 while ((c
= tunnel
[t
].controls
))
1173 controlt
* n
= c
->next
;
1174 tunnel
[t
].controls
= n
;
1175 tunnel
[t
].controlc
--;
1176 c
->next
= controlfree
;
1180 for (s
= 1; s
< MAXSESSION
; s
++)
1181 if (session
[s
].tunnel
== t
)
1182 sessionkill(s
, reason
);
1186 LOG(1, 0, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1187 cli_tunnel_actions
[s
].action
= 0;
1188 cluster_send_tunnel(t
);
1191 // shut down a tunnel cleanly
1192 void tunnelshutdown(tunnelidt t
, char *reason
)
1196 CSTAT(call_tunnelshutdown
);
1198 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1200 // never set up, can immediately kill
1201 tunnelkill(t
, reason
);
1204 LOG(1, 0, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1207 for (s
= 1; s
< MAXSESSION
; s
++)
1208 if (session
[s
].tunnel
== t
)
1209 sessionkill(s
, reason
);
1211 tunnel
[t
].state
= TUNNELDIE
;
1212 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
1213 cluster_send_tunnel(t
);
1214 // TBA - should we wait for sessions to stop?
1216 controlt
*c
= controlnew(4); // sending StopCCN
1217 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message
1218 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1219 controladd(c
, t
, 0); // send the message
1223 // read and process packet on tunnel (UDP)
1224 void processudp(u8
* buf
, int len
, struct sockaddr_in
*addr
)
1226 char *chapresponse
= NULL
;
1227 u16 l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1231 CSTAT(call_processudp
);
1235 LOG_HEX(5, "UDP Data", buf
, len
);
1236 STAT(tunnel_rx_packets
);
1237 INC_STAT(tunnel_rx_bytes
, len
);
1240 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Short UDP, %d bytes\n", len
);
1241 STAT(tunnel_rx_errors
);
1244 if ((buf
[1] & 0x0F) != 2)
1246 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1247 STAT(tunnel_rx_errors
);
1252 l
= ntohs(*(u16
*) p
);
1255 t
= ntohs(*(u16
*) p
);
1257 s
= ntohs(*(u16
*) p
);
1259 if (s
>= MAXSESSION
)
1261 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid session ID\n");
1262 STAT(tunnel_rx_errors
);
1267 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid tunnel ID\n");
1268 STAT(tunnel_rx_errors
);
1273 ns
= ntohs(*(u16
*) p
);
1275 nr
= ntohs(*(u16
*) p
);
1280 u16 o
= ntohs(*(u16
*) p
);
1285 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad length %d>%d\n", (p
- buf
), l
);
1286 STAT(tunnel_rx_errors
);
1292 u16 message
= 0xFFFF; // message type
1294 u8 mandatorymessage
= 0;
1295 u8 chap
= 0; // if CHAP being used
1296 u16 asession
= 0; // assigned session
1297 u32 amagic
= 0; // magic number
1298 u8 aflags
= 0; // flags from last LCF
1299 u16 version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1300 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1301 char called
[MAXTEL
] = ""; // called number
1302 char calling
[MAXTEL
] = ""; // calling number
1304 if (!config
->cluster_iam_master
)
1306 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1310 if ((*buf
& 0xCA) != 0xC8)
1312 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad control header %02X\n", *buf
);
1313 STAT(tunnel_rx_errors
);
1316 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",
1317 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1318 // if no tunnel specified, assign one
1324 // Is this a duplicate of the first packet? (SCCRQ)
1326 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1328 if (tunnel
[i
].state
!= TUNNELOPENING
||
1329 tunnel
[i
].ip
!= ntohl(*(ipt
*) & addr
->sin_addr
) ||
1330 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1339 if (!(t
= new_tunnel()))
1341 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "No more tunnels\n");
1342 STAT(tunnel_overflow
);
1346 tunnel
[t
].ip
= ntohl(*(ipt
*) & addr
->sin_addr
);
1347 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1348 tunnel
[t
].window
= 4; // default window
1349 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
);
1350 STAT(tunnel_created
);
1353 // This is used to time out old tunnels
1354 tunnel
[t
].lastrec
= time_now
;
1356 // check sequence of this message
1358 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1359 // some to clear maybe?
1360 while (tunnel
[t
].controlc
&& (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1362 controlt
*c
= tunnel
[t
].controls
;
1363 tunnel
[t
].controls
= c
->next
;
1364 tunnel
[t
].controlc
--;
1365 c
->next
= controlfree
;
1368 tunnel
[t
].try = 0; // we have progress
1371 // If the 'ns' just received is not the 'nr' we're
1372 // expecting, just send an ack and drop it.
1374 // if 'ns' is less, then we got a retransmitted packet.
1375 // if 'ns' is greater than missed a packet. Either way
1376 // we should ignore it.
1377 if (ns
!= tunnel
[t
].nr
)
1379 // is this the sequence we were expecting?
1380 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
);
1381 STAT(tunnel_rx_errors
);
1383 if (l
) // Is this not a ZLB?
1387 // receiver advance (do here so quoted correctly in any sends below)
1388 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1389 if (skip
< 0) skip
= 0;
1390 if (skip
< tunnel
[t
].controlc
)
1392 // some control packets can now be sent that were previous stuck out of window
1393 int tosend
= tunnel
[t
].window
- skip
;
1394 controlt
*c
= tunnel
[t
].controls
;
1402 tunnel
[t
].try = 0; // first send
1403 tunnelsend(c
->buf
, c
->length
, t
);
1408 if (!tunnel
[t
].controlc
)
1409 tunnel
[t
].retry
= 0; // caught up
1412 { // if not a null message
1414 while (l
&& !(fatal
& 0x80))
1416 u16 n
= (ntohs(*(u16
*) p
) & 0x3FF);
1423 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Invalid length in AVP\n");
1424 STAT(tunnel_rx_errors
);
1431 // handle hidden AVPs
1432 if (!*config
->l2tpsecret
)
1434 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1438 if (!session
[s
].random_vector_length
)
1440 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no random vector.\n");
1444 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP\n");
1446 n
= unhide_avp(b
, t
, s
, n
);
1455 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1462 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown AVP vendor %d\n", ntohs(*(u16
*) (b
)));
1467 mtype
= ntohs(*(u16
*) (b
));
1471 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1474 case 0: // message type
1475 message
= ntohs(*(u16
*) b
);
1476 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Message type = %d (%s)\n", *b
,
1477 l2tp_message_types
[message
]);
1478 mandatorymessage
= flags
;
1480 case 1: // result code
1482 u16 rescode
= ntohs(*(u16
*)(b
));
1483 const char* resdesc
= "(unknown)";
1486 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1487 resdesc
= stopccn_result_codes
[rescode
];
1489 else if (message
== 14)
1491 if (rescode
<= MAX_CDN_RESULT_CODE
)
1492 resdesc
= cdn_result_codes
[rescode
];
1495 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Result Code %d: %s\n",
1499 u16 errcode
= ntohs(*(u16
*)(b
+ 2));
1500 const char* errdesc
= "(unknown)";
1501 if (errcode
<= MAX_ERROR_CODE
)
1502 errdesc
= error_codes
[errcode
];
1503 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error Code %d: %s\n",
1507 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error String: %.*s\n",
1513 case 2: // protocol version
1515 version
= ntohs(*(u16
*) (b
));
1516 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Protocol version = %d\n", version
);
1517 if (version
&& version
!= 0x0100)
1518 { // allow 0.0 and 1.0
1519 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Bad protocol version %04X\n",
1526 case 3: // framing capabilities
1527 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Framing capabilities\n");
1529 case 4: // bearer capabilities
1530 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Bearer capabilities\n");
1532 case 5: // tie breaker
1533 // We never open tunnels, so we don't care about tie breakers
1534 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Tie breaker\n");
1536 case 6: // firmware revision
1537 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Firmware revision\n");
1539 case 7: // host name
1540 memset(tunnel
[t
].hostname
, 0, 128);
1541 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1542 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1543 // TBA - to send to RADIUS
1545 case 8: // vendor name
1546 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1547 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1548 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1550 case 9: // assigned tunnel
1551 tunnel
[t
].far
= ntohs(*(u16
*) (b
));
1552 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1554 case 10: // rx window
1555 tunnel
[t
].window
= ntohs(*(u16
*) (b
));
1556 if (!tunnel
[t
].window
)
1557 tunnel
[t
].window
= 1; // window of 0 is silly
1558 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1560 case 11: // Challenge
1562 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " LAC requested CHAP authentication for tunnel\n");
1563 build_chap_response(b
, 2, n
, &chapresponse
);
1566 case 13: // Response
1567 // Why did they send a response? We never challenge.
1568 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " received unexpected challenge response\n");
1571 case 14: // assigned session
1572 asession
= session
[s
].far
= ntohs(*(u16
*) (b
));
1573 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " assigned session = %d\n", asession
);
1575 case 15: // call serial number
1576 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " call serial number = %d\n", ntohl(*(u32
*)b
));
1578 case 18: // bearer type
1579 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " bearer type = %d\n", ntohl(*(u32
*)b
));
1582 case 19: // framing type
1583 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " framing type = %d\n", ntohl(*(u32
*)b
));
1586 case 21: // called number
1587 memset(called
, 0, MAXTEL
);
1588 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1589 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Called <%s>\n", called
);
1591 case 22: // calling number
1592 memset(calling
, 0, MAXTEL
);
1593 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1594 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Calling <%s>\n", calling
);
1598 case 24: // tx connect speed
1601 session
[s
].tx_connect_speed
= ntohl(*(u32
*)b
);
1605 // AS5300s send connect speed as a string
1607 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1608 session
[s
].tx_connect_speed
= atol(tmp
);
1610 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " TX connect speed <%u>\n",
1611 session
[s
].tx_connect_speed
);
1613 case 38: // rx connect speed
1616 session
[s
].rx_connect_speed
= ntohl(*(u32
*)b
);
1620 // AS5300s send connect speed as a string
1622 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1623 session
[s
].rx_connect_speed
= atol(tmp
);
1625 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " RX connect speed <%u>\n",
1626 session
[s
].rx_connect_speed
);
1628 case 25: // Physical Channel ID
1630 u32 tmp
= ntohl(*(u32
*)b
);
1631 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Physical Channel ID <%X>\n", tmp
);
1634 case 29: // Proxy Authentication Type
1636 u16 authtype
= ntohs(*(u16
*)b
);
1637 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Type %d (%s)\n",
1638 authtype
, authtypes
[authtype
]);
1639 requestchap
= (authtype
== 2);
1642 case 30: // Proxy Authentication Name
1644 char authname
[64] = {0};
1645 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1646 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Name (%s)\n",
1650 case 31: // Proxy Authentication Challenge
1652 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1653 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Challenge\n");
1656 case 32: // Proxy Authentication ID
1658 u16 authid
= ntohs(*(u16
*)(b
));
1659 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth ID (%d)\n",
1661 if (session
[s
].radius
)
1662 radius
[session
[s
].radius
].id
= authid
;
1665 case 33: // Proxy Authentication Response
1667 char authresp
[64] = {0};
1668 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1669 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Response\n");
1672 case 27: // last send lcp
1673 { // find magic number
1674 u8
*p
= b
, *e
= p
+ n
;
1675 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1677 if (*p
== 5 && p
[1] == 6) // Magic-Number
1678 amagic
= ntohl(*(u32
*) (p
+ 2));
1679 else if (*p
== 3 && p
[1] == 5 && *(u16
*) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1681 else if (*p
== 7) // Protocol-Field-Compression
1682 aflags
|= SESSIONPFC
;
1683 else if (*p
== 8) // Address-and-Control-Field-Compression
1684 aflags
|= SESSIONACFC
;
1689 case 28: // last recv lcp confreq
1691 case 26: // Initial Received LCP CONFREQ
1693 case 39: // seq required - we control it as an LNS anyway...
1695 case 36: // Random Vector
1696 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1697 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1698 memcpy(session
[s
].random_vector
, b
, n
);
1699 session
[s
].random_vector_length
= n
;
1702 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Unknown AVP type %d\n", mtype
);
1709 tunnelshutdown(t
, "Unknown Mandatory AVP");
1713 case 1: // SCCRQ - Start Control Connection Request
1715 controlt
*c
= controlnew(2); // sending SCCRP
1716 control16(c
, 2, version
, 1); // protocol version
1717 control32(c
, 3, 3, 1); // framing
1718 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1719 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1720 control16(c
, 9, t
, 1); // assigned tunnel
1721 controladd(c
, t
, s
); // send the resply
1723 tunnel
[t
].state
= TUNNELOPENING
;
1726 tunnel
[t
].state
= TUNNELOPEN
;
1729 tunnel
[t
].state
= TUNNELOPEN
;
1730 controlnull(t
); // ack
1733 controlnull(t
); // ack
1734 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1735 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1738 controlnull(t
); // simply ACK
1752 STAT(session_overflow
);
1753 tunnelshutdown(t
, "No free sessions");
1761 sessionfree
= session
[s
].next
;
1762 memset(&session
[s
], 0, sizeof(session
[s
]));
1764 if (s
> config
->cluster_highest_sessionid
)
1765 config
->cluster_highest_sessionid
= s
;
1767 // make a RADIUS session
1768 if (!(r
= radiusnew(s
)))
1770 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "No free RADIUS sessions for ICRQ\n");
1771 sessionkill(s
, "no free RADIUS sesions");
1775 c
= controlnew(11); // sending ICRP
1776 session
[s
].id
= sessionid
++;
1777 session
[s
].opened
= time(NULL
);
1778 session
[s
].tunnel
= t
;
1779 session
[s
].far
= asession
;
1780 session
[s
].last_packet
= time_now
;
1781 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1782 control16(c
, 14, s
, 1); // assigned session
1783 controladd(c
, t
, s
); // send the reply
1785 // Generate a random challenge
1787 for (n
= 0; n
< 15; n
++)
1788 radius
[r
].auth
[n
] = rand();
1790 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1791 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1792 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1793 STAT(session_created
);
1800 if (amagic
== 0) amagic
= time_now
;
1801 session
[s
].magic
= amagic
; // set magic number
1802 session
[s
].l2tp_flags
= aflags
; // set flags received
1803 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1804 controlnull(t
); // ack
1805 // In CHAP state, request PAP instead
1810 controlnull(t
); // ack
1811 sessionshutdown(s
, "Closed (Received CDN)");
1814 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Missing message type\n");
1817 STAT(tunnel_rx_errors
);
1818 if (mandatorymessage
& 0x80)
1819 tunnelshutdown(t
, "Unknown message");
1821 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown message type %d\n", message
);
1824 if (chapresponse
) free(chapresponse
);
1825 cluster_send_tunnel(t
);
1829 LOG(4, 0, s
, t
, " Got a ZLB ack\n");
1836 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
1837 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1838 { // HDLC address header, discard
1844 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Short ppp length %d\n", l
);
1845 STAT(tunnel_rx_errors
);
1855 prot
= ntohs(*(u16
*) p
);
1860 if (s
&& !session
[s
].tunnel
) // Is something wrong??
1862 if (!config
->cluster_iam_master
)
1864 // Pass it off to the master to deal with..
1865 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1870 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "UDP packet contains session %d "
1871 "but no session[%d].tunnel exists (LAC said"
1872 " tunnel = %d). Dropping packet.\n", s
, s
, t
);
1873 STAT(tunnel_rx_errors
);
1879 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1880 // I'm pretty sure this isn't right -- mo.
1881 // return; // closing session, PPP not processed
1885 session
[s
].last_packet
= time_now
;
1886 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1887 processpap(t
, s
, p
, l
);
1889 else if (prot
== PPPCHAP
)
1891 session
[s
].last_packet
= time_now
;
1892 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1893 processchap(t
, s
, p
, l
);
1895 else if (prot
== PPPLCP
)
1897 session
[s
].last_packet
= time_now
;
1898 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1899 processlcp(t
, s
, p
, l
);
1901 else if (prot
== PPPIPCP
)
1903 session
[s
].last_packet
= time_now
;
1904 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1905 processipcp(t
, s
, p
, l
);
1907 else if (prot
== PPPCCP
)
1909 session
[s
].last_packet
= time_now
;
1910 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1911 processccp(t
, s
, p
, l
);
1913 else if (prot
== PPPIP
)
1915 session
[s
].last_packet
= time_now
;
1916 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
1918 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1921 processipin(t
, s
, p
, l
);
1925 STAT(tunnel_rx_errors
);
1926 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown PPP protocol %04X\n", prot
);
1931 // read and process packet on tun
1932 void processtun(u8
* buf
, int len
)
1934 LOG_HEX(5, "Receive TUN Data", buf
, len
);
1935 STAT(tun_rx_packets
);
1936 INC_STAT(tun_rx_bytes
, len
);
1938 CSTAT(call_processtun
);
1944 LOG(1, 0, 0, 0, "Short tun packet %d bytes\n", len
);
1945 STAT(tun_rx_errors
);
1949 if (*(u16
*) (buf
+ 2) == htons(PKTIP
)) // IP
1950 processipout(buf
, len
);
1955 // Maximum number of actions to complete.
1956 // This is to avoid sending out too many packets
1958 #define MAX_ACTIONS 500
1960 int regular_cleanups(void)
1962 static sessionidt s
= 0; // Next session to check for actions on.
1966 static clockt next_acct
= 0;
1969 LOG(3, 0, 0, 0, "Begin regular cleanup\n");
1971 for (r
= 1; r
< MAXRADIUS
; r
++)
1973 if (!radius
[r
].state
)
1975 if (radius
[r
].retry
)
1977 if (radius
[r
].retry
<= TIME
)
1980 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
1982 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
1984 // check for expired tunnels
1985 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
1987 STAT(tunnel_timeout
);
1988 tunnelkill(t
, "Expired");
1991 // check for message resend
1992 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
1994 // resend pending messages as timeout on reply
1995 if (tunnel
[t
].retry
<= TIME
)
1997 controlt
*c
= tunnel
[t
].controls
;
1998 u8 w
= tunnel
[t
].window
;
1999 tunnel
[t
].try++; // another try
2000 if (tunnel
[t
].try > 5)
2001 tunnelkill(t
, "Timeout on control message"); // game over
2005 tunnelsend(c
->buf
, c
->length
, t
);
2011 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2013 controlt
*c
= controlnew(6); // sending HELLO
2014 controladd(c
, t
, 0); // send the message
2015 LOG(3, tunnel
[t
].ip
, 0, t
, "Sending HELLO message\n");
2018 // Check for tunnel changes requested from the CLI
2019 if ((a
= cli_tunnel_actions
[t
].action
))
2021 cli_tunnel_actions
[t
].action
= 0;
2022 if (a
& CLI_TUN_KILL
)
2024 LOG(2, tunnel
[t
].ip
, 0, t
, "Dropping tunnel by CLI\n");
2025 tunnelshutdown(t
, "Requested by administrator");
2032 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2035 if (s
> config
->cluster_highest_sessionid
)
2038 if (!session
[s
].tunnel
) // Session isn't in use
2041 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2043 // IPCP has not completed yet. Resend
2044 LOG(3, session
[s
].ip
, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2045 sendipcp(session
[s
].tunnel
, s
);
2048 // check for expired sessions
2049 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2051 sessionkill(s
, "Expired");
2052 if (++count
>= MAX_ACTIONS
) break;
2056 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2057 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2059 sessionkill(s
, "No response to LCP ECHO requests");
2060 STAT(session_timeout
);
2061 if (++count
>= MAX_ACTIONS
) break;
2065 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2066 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2068 u8 b
[MAXCONTROL
] = {0};
2070 u8
*q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2073 LOG(3, session
[s
].ip
, s
, t
, "failed to send ECHO packet.\n");
2078 *(u8
*)(q
+ 1) = (time_now
% 255); // ID
2079 *(u16
*)(q
+ 2) = htons(8); // Length
2080 *(u32
*)(q
+ 4) = 0; // Magic Number (not supported)
2082 LOG(4, session
[s
].ip
, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2083 (int)(time_now
- session
[s
].last_packet
));
2084 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2085 if (++count
>= MAX_ACTIONS
) break;
2088 // Check for actions requested from the CLI
2089 if ((a
= cli_session_actions
[s
].action
))
2093 cli_session_actions
[s
].action
= 0;
2094 if (a
& CLI_SESS_KILL
)
2096 LOG(2, 0, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2097 sessionshutdown(s
, "Requested by administrator");
2098 a
= 0; // dead, no need to check for other actions
2101 if (a
& CLI_SESS_NOSNOOP
)
2103 LOG(2, 0, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2104 session
[s
].snoop_ip
= 0;
2105 session
[s
].snoop_port
= 0;
2108 else if (a
& CLI_SESS_SNOOP
)
2110 LOG(2, 0, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2111 inet_toa(cli_session_actions
[s
].snoop_ip
), cli_session_actions
[s
].snoop_port
);
2113 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2114 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2118 if (a
& CLI_SESS_NOTHROTTLE
)
2120 LOG(2, 0, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2121 throttle_session(s
, 0, 0);
2124 else if (a
& CLI_SESS_THROTTLE
)
2126 LOG(2, 0, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2127 cli_session_actions
[s
].throttle_in
,
2128 cli_session_actions
[s
].throttle_out
);
2130 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2135 cluster_send_session(s
);
2137 if (++count
>= MAX_ACTIONS
) break;
2141 if (*config
->accounting_dir
&& next_acct
<= TIME
)
2143 // Dump accounting data
2144 next_acct
= TIME
+ ACCT_TIME
;
2148 if (count
>= MAX_ACTIONS
)
2149 return 1; // Didn't finish!
2151 LOG(3, 0, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count
, config
->cleanup_interval
);
2157 // Are we in the middle of a tunnel update, or radius
2160 int still_busy(void)
2163 static clockt last_talked
= 0;
2164 static clockt start_busy_wait
= 0;
2165 if (start_busy_wait
== 0)
2166 start_busy_wait
= TIME
;
2168 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2170 if (!tunnel
[i
].controlc
)
2173 if (last_talked
!= TIME
)
2175 LOG(2,0,0,0, "Tunnel %d still has un-acked control messages.\n", i
);
2181 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2182 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2184 LOG(1, 0, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2188 for (i
= 1; i
< MAXRADIUS
; i
++)
2190 if (radius
[i
].state
== RADIUSNULL
)
2192 if (radius
[i
].state
== RADIUSWAIT
)
2195 if (last_talked
!= TIME
)
2197 LOG(2,0,0,0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2206 static fd_set readset
;
2207 static int readset_n
= 0;
2209 // main loop - gets packets on tun or udp and processes them
2215 clockt next_cluster_ping
= 0; // send initial ping immediately
2216 time_t next_clean
= time_now
+ config
->cleanup_interval
;
2218 LOG(4, 0, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2219 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2222 FD_SET(udpfd
, &readset
);
2223 FD_SET(tunfd
, &readset
);
2224 FD_SET(controlfd
, &readset
);
2225 FD_SET(clifd
, &readset
);
2226 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2228 if (tunfd
> readset_n
) readset_n
= tunfd
;
2229 if (controlfd
> readset_n
) readset_n
= controlfd
;
2230 if (clifd
> readset_n
) readset_n
= clifd
;
2231 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2233 while (!main_quit
|| still_busy())
2239 int bgp_set
[BGP_NUM_PEERS
];
2242 if (config
->reload_config
)
2244 // Update the config state based on config settings
2248 memcpy(&r
, &readset
, sizeof(fd_set
));
2250 to
.tv_usec
= 100000; // 1/10th of a second.
2254 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2256 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2259 FD_SET(bgp_peers
[i
].sock
, &r
);
2260 if (bgp_peers
[i
].sock
> n
)
2261 n
= bgp_peers
[i
].sock
;
2266 FD_SET(bgp_peers
[i
].sock
, &w
);
2267 if (bgp_peers
[i
].sock
> n
)
2268 n
= bgp_peers
[i
].sock
;
2272 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2274 n
= select(n
+ 1, &r
, 0, 0, &to
);
2280 if (errno
== EINTR
||
2281 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2284 LOG(0, 0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2290 struct sockaddr_in addr
;
2291 int alen
= sizeof(addr
);
2292 if (FD_ISSET(udpfd
, &r
))
2295 for (c
= 0; c
< config
->multi_read_count
; c
++)
2297 if ((n
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
2298 processudp(buf
, n
, &addr
);
2303 if (FD_ISSET(tunfd
, &r
))
2306 for (c
= 0; c
< config
->multi_read_count
; c
++)
2308 if ((n
= read(tunfd
, buf
, sizeof(buf
))) > 0)
2315 if (config
->cluster_iam_master
)
2316 for (i
= 0; i
< config
->num_radfds
; i
++)
2317 if (FD_ISSET(radfds
[i
], &r
))
2318 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2320 if (FD_ISSET(cluster_sockfd
, &r
))
2323 size
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
);
2324 processcluster(buf
, size
, addr
.sin_addr
.s_addr
);
2327 if (FD_ISSET(controlfd
, &r
))
2328 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
);
2330 if (FD_ISSET(clifd
, &r
))
2332 struct sockaddr_in addr
;
2334 int len
= sizeof(addr
);
2336 if ((sockfd
= accept(clifd
, (struct sockaddr
*)&addr
, &len
)) <= 0)
2338 LOG(0, 0, 0, 0, "accept error: %s\n", strerror(errno
));
2349 // Runs on every machine (master and slaves).
2350 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
2352 // Check to see which of the cluster is still alive..
2354 cluster_send_ping(basetime
); // Only does anything if we're a slave
2355 cluster_check_master(); // ditto.
2357 cluster_heartbeat(); // Only does anything if we're a master.
2358 cluster_check_slaves(); // ditto.
2360 master_update_counts(); // If we're a slave, send our byte counters to our master.
2362 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
2363 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
2365 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
2368 // Run token bucket filtering queue..
2369 // Only run it every 1/10th of a second.
2370 // Runs on all machines both master and slave.
2372 static clockt last_run
= 0;
2373 if (last_run
!= TIME
)
2380 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2381 * something to read, else under load this will never actually run....
2384 if (config
->cluster_iam_master
&& next_clean
<= time_now
)
2386 if (regular_cleanups())
2389 next_clean
= time_now
+ 1 ; // Didn't finish. Check quickly.
2393 next_clean
= time_now
+ config
->cleanup_interval
; // Did. Move to next interval.
2398 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2400 bgp_process(&bgp_peers
[i
],
2401 bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0,
2402 bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0);
2407 // Are we the master and shutting down??
2408 if (config
->cluster_iam_master
)
2409 cluster_heartbeat(); // Flush any queued changes..
2411 // Ok. Notify everyone we're shutting down. If we're
2412 // the master, this will force an election.
2413 cluster_send_ping(0);
2416 // Important!!! We MUST not process any packets past this point!
2419 static void stripdomain(char *host
)
2423 if ((p
= strchr(host
, '.')))
2429 FILE *resolv
= fopen("/etc/resolv.conf", "r");
2435 while (fgets(buf
, sizeof(buf
), resolv
))
2437 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
2440 if (!isspace(buf
[6]))
2444 while (isspace(*b
)) b
++;
2449 while (*b
&& !isspace(*b
)) b
++;
2451 if (buf
[0] == 'd') // domain is canonical
2457 // first search line
2460 // hold, may be subsequent domain line
2461 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
2472 int hl
= strlen(host
);
2473 int dl
= strlen(domain
);
2474 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
2475 host
[hl
-dl
- 1] = 0;
2479 *p
= 0; // everything after first dot
2484 // Init data structures
2485 void initdata(int optdebug
, char *optconfig
)
2489 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
2491 LOG(0, 0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
2494 if (!(config
= shared_malloc(sizeof(struct configt
))))
2496 LOG(0, 0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2499 memset(config
, 0, sizeof(struct configt
));
2500 time(&config
->start_time
);
2501 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
2502 config
->debug
= optdebug
;
2503 config
->num_tbfs
= MAXTBFS
;
2504 config
->rl_rate
= 28; // 28kbps
2506 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
2508 LOG(0, 0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
2511 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
2513 LOG(0, 0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
2517 if (!(sess_count
= shared_malloc(sizeof(sessioncountt
) * MAXSESSION
)))
2519 LOG(0, 0, 0, 0, "Error doing malloc for sessions_count: %s\n", strerror(errno
));
2523 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
2525 LOG(0, 0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
2529 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
2531 LOG(0, 0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
2536 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2538 LOG(0, 0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2541 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2544 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2546 LOG(0, 0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2549 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2551 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2553 LOG(0, 0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2556 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2558 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2559 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2560 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2561 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2563 // Put all the sessions on the free list marked as undefined.
2564 for (i
= 1; i
< MAXSESSION
- 1; i
++)
2566 session
[i
].next
= i
+ 1;
2567 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2569 session
[MAXSESSION
- 1].next
= 0;
2572 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2573 for (i
= 1; i
< MAXTUNNEL
- 1; i
++)
2574 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2578 // Grab my hostname unless it's been specified
2579 gethostname(hostname
, sizeof(hostname
));
2580 stripdomain(hostname
);
2583 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2586 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2588 LOG(0, 0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2594 void initiptables(void)
2596 /* Flush the tables here so that we have a clean slate */
2598 // Not needed. 'nat' is setup by garden.c
2599 // mangle isn't used (as throttling is done by tbf inhouse).
2602 int assign_ip_address(sessionidt s
)
2606 time_t best_time
= time_now
;
2607 char *u
= session
[s
].user
;
2611 CSTAT(call_assign_ip_address
);
2613 for (i
= 1; i
< ip_pool_size
; i
++)
2615 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2618 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2625 if (ip_address_pool
[i
].last
< best_time
)
2628 if (!(best_time
= ip_address_pool
[i
].last
))
2629 break; // never used, grab this one
2635 LOG(0, 0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2639 session
[s
].ip
= ip_address_pool
[best
].address
;
2640 session
[s
].ip_pool_index
= best
;
2641 ip_address_pool
[best
].assigned
= 1;
2642 ip_address_pool
[best
].last
= time_now
;
2643 ip_address_pool
[best
].session
= s
;
2644 if (session
[s
].walled_garden
)
2645 /* Don't track addresses of users in walled garden (note: this
2646 means that their address isn't "sticky" even if they get
2648 ip_address_pool
[best
].user
[0] = 0;
2650 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2653 LOG(4, ip_address_pool
[best
].address
, s
, session
[s
].tunnel
,
2654 "assign_ip_address(): %s ip address %d from pool\n", reuse
? "Reusing" : "Allocating", best
);
2659 void free_ip_address(sessionidt s
)
2661 int i
= session
[s
].ip_pool_index
;
2664 return; // what the?
2666 if (i
< 0) // Is this actually part of the ip pool?
2670 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2672 ip_address_pool
[i
].assigned
= 0;
2673 ip_address_pool
[i
].session
= 0;
2674 ip_address_pool
[i
].last
= time_now
;
2677 CSTAT(call_free_ip_address
);
2682 // Fsck the address pool against the session table.
2683 // Normally only called when we become a master.
2685 // This isn't perfect: We aren't keep tracking of which
2686 // users used to have an IP address.
2688 void rebuild_address_pool(void)
2693 // Zero the IP pool allocation, and build
2694 // a map from IP address to pool index.
2695 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2697 ip_address_pool
[i
].assigned
= 0;
2698 ip_address_pool
[i
].session
= 0;
2699 if (!ip_address_pool
[i
].address
)
2702 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2705 for (i
= 0; i
< MAXSESSION
; ++i
)
2708 if (!session
[i
].ip
|| !session
[i
].tunnel
)
2710 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2712 if (session
[i
].ip_pool_index
< 0)
2714 // Not allocated out of the pool.
2715 if (ipid
< 1) // Not found in the pool either? good.
2718 LOG(0, 0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2719 i
, inet_toa(session
[i
].ip
), ipid
);
2721 // Fall through and process it as part of the pool.
2725 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2727 LOG(0, 0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2729 session
[i
].ip_pool_index
= ipid
;
2733 ip_address_pool
[ipid
].assigned
= 1;
2734 ip_address_pool
[ipid
].session
= i
;
2735 ip_address_pool
[ipid
].last
= time_now
;
2736 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2737 session
[i
].ip_pool_index
= ipid
;
2738 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
2743 // Fix the address pool to match a changed session.
2744 // (usually when the master sends us an update).
2745 void fix_address_pool(int sid
)
2749 ipid
= session
[sid
].ip_pool_index
;
2751 if (ipid
> ip_pool_size
)
2752 return; // Ignore it. rebuild_address_pool will fix it up.
2754 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
2755 return; // Just ignore it. rebuild_address_pool will take care of it.
2757 ip_address_pool
[ipid
].assigned
= 1;
2758 ip_address_pool
[ipid
].session
= sid
;
2759 ip_address_pool
[ipid
].last
= time_now
;
2760 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2764 // Add a block of addresses to the IP pool to hand out.
2766 void add_to_ip_pool(u32 addr
, u32 mask
)
2770 mask
= 0xffffffff; // Host route only.
2774 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
2777 for (i
= addr
;(i
& mask
) == addr
; ++i
)
2779 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
2780 continue; // Skip 0 and broadcast addresses.
2782 ip_address_pool
[ip_pool_size
].address
= i
;
2783 ip_address_pool
[ip_pool_size
].assigned
= 0;
2785 if (ip_pool_size
>= MAXIPPOOL
)
2787 LOG(0,0,0,0, "Overflowed IP pool adding %s\n", inet_toa(htonl(addr
)) );
2793 // Initialize the IP address pool
2799 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2801 if (!(f
= fopen(IPPOOLFILE
, "r")))
2803 LOG(0, 0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2807 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2810 buf
[4095] = 0; // Force it to be zero terminated/
2812 if (*buf
== '#' || *buf
== '\n')
2813 continue; // Skip comments / blank lines
2814 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2815 if ((p
= (char *)strchr(buf
, ':')))
2819 src
= inet_addr(buf
);
2820 if (src
== INADDR_NONE
)
2822 LOG(0, 0, 0, 0, "Invalid address pool IP %s\n", buf
);
2825 // This entry is for a specific IP only
2826 if (src
!= config
->bind_address
)
2831 if ((p
= (char *)strchr(pool
, '/')))
2835 u32 start
= 0, mask
= 0;
2837 LOG(2, 0, 0, 0, "Adding IP address range %s\n", buf
);
2839 if (!*p
|| !(numbits
= atoi(p
)))
2841 LOG(0, 0, 0, 0, "Invalid pool range %s\n", buf
);
2844 start
= ntohl(inet_addr(pool
));
2845 mask
= (u32
)(pow(2, numbits
) - 1) << (32 - numbits
);
2847 // Add a static route for this pool
2848 LOG(5, 0, 0, 0, "Adding route for address pool %s/%u\n", inet_toa(htonl(start
)), 32 + mask
);
2849 routeset(0, start
, mask
, 0, 1);
2851 add_to_ip_pool(start
, mask
);
2855 // It's a single ip address
2856 add_to_ip_pool(inet_addr(pool
), 0);
2860 LOG(1, 0, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
2863 void snoop_send_packet(char *packet
, u16 size
, ipt destination
, u16 port
)
2865 struct sockaddr_in snoop_addr
= {0};
2866 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2869 snoop_addr
.sin_family
= AF_INET
;
2870 snoop_addr
.sin_addr
.s_addr
= destination
;
2871 snoop_addr
.sin_port
= ntohs(port
);
2873 LOG(5, 0, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n",
2874 packet
, size
, inet_toa(snoop_addr
.sin_addr
.s_addr
), htons(snoop_addr
.sin_port
));
2875 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
2876 LOG(0, 0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
2877 STAT(packets_snooped
);
2880 void dump_acct_info()
2882 char filename
[1024];
2884 time_t t
= time(NULL
);
2889 CSTAT(call_dump_acct_info
);
2891 strftime(timestr
, 64, "%Y%m%d%H%M%S", localtime(&t
));
2892 snprintf(filename
, 1024, "%s/%s", config
->accounting_dir
, timestr
);
2894 for (i
= 0; i
< MAXSESSION
; i
++)
2896 if (!session
[i
].opened
|| !session
[i
].ip
|| !(session
[i
].cin
|| session
[i
].cout
) || !*session
[i
].user
|| session
[i
].walled_garden
)
2900 time_t now
= time(NULL
);
2901 if (!(f
= fopen(filename
, "w")))
2903 LOG(0, 0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
2906 LOG(3, 0, 0, 0, "Dumping accounting information to %s\n", filename
);
2907 fprintf(f
, "# dslwatch.pl dump file V1.01\n"
2911 "# format: username ip qos uptxoctets downrxoctets\n",
2917 LOG(4, 0, 0, 0, "Dumping accounting information for %s\n", session
[i
].user
);
2918 fprintf(f
, "%s %s %d %u %u\n",
2919 session
[i
].user
, // username
2920 inet_toa(htonl(session
[i
].ip
)), // ip
2921 (session
[i
].throttle_in
|| session
[i
].throttle_out
) ? 2 : 1, // qos
2922 (u32
)session
[i
].cin
, // uptxoctets
2923 (u32
)session
[i
].cout
); // downrxoctets
2925 session
[i
].pin
= session
[i
].cin
= 0;
2926 session
[i
].pout
= session
[i
].cout
= 0;
2934 int main(int argc
, char *argv
[])
2938 char *optconfig
= CONFIGFILE
;
2940 _program_name
= strdup(argv
[0]);
2942 time(&basetime
); // start clock
2945 while ((o
= getopt(argc
, argv
, "dvc:h:")) >= 0)
2950 if (fork()) exit(0);
2952 freopen("/dev/null", "r", stdin
);
2953 freopen("/dev/null", "w", stdout
);
2954 freopen("/dev/null", "w", stderr
);
2963 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
2966 printf("Args are:\n"
2967 "\t-d\tDetach from terminal\n"
2968 "\t-c <file>\tConfig file\n"
2969 "\t-h <hostname>\tForce hostname\n"
2970 "\t-a <address>\tUse specific address\n"
2978 // Start the timer routine off
2980 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
2981 signal(SIGALRM
, sigalrm_handler
);
2982 siginterrupt(SIGALRM
, 0);
2986 initdata(optdebug
, optconfig
);
2990 init_tbf(config
->num_tbfs
);
2992 LOG(0, 0, 0, 0, "L2TPNS version " VERSION
"\n");
2993 LOG(0, 0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
2994 LOG(0, 0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
2997 rlim
.rlim_cur
= RLIM_INFINITY
;
2998 rlim
.rlim_max
= RLIM_INFINITY
;
2999 // Remove the maximum core size
3000 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
3001 LOG(0, 0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
3002 // Make core dumps go to /tmp
3006 if (config
->scheduler_fifo
)
3009 struct sched_param params
= {0};
3010 params
.sched_priority
= 1;
3012 if (get_nprocs() < 2)
3014 LOG(0, 0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3015 config
->scheduler_fifo
= 0;
3019 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3021 LOG(1, 0, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3025 LOG(0, 0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3026 config
->scheduler_fifo
= 0;
3031 /* Set up the cluster communications port. */
3032 if (cluster_init(config
->bind_address
) < 0)
3036 signal(SIGPIPE
, SIG_IGN
);
3037 bgp_setup(config
->as_number
);
3038 bgp_add_route(config
->bind_address
, 0xffffffff);
3039 if (*config
->bgp_peer
[0])
3040 bgp_start(&bgp_peers
[0], config
->bgp_peer
[0],
3041 config
->bgp_peer_as
[0], 0); /* 0 = routing disabled */
3043 if (*config
->bgp_peer
[1])
3044 bgp_start(&bgp_peers
[1], config
->bgp_peer
[1],
3045 config
->bgp_peer_as
[1], 0);
3049 LOG(1, 0, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3057 signal(SIGHUP
, sighup_handler
);
3058 signal(SIGTERM
, sigterm_handler
);
3059 signal(SIGINT
, sigterm_handler
);
3060 signal(SIGQUIT
, sigquit_handler
);
3061 signal(SIGCHLD
, sigchild_handler
);
3063 // Prevent us from getting paged out
3064 if (config
->lock_pages
)
3066 if (!mlockall(MCL_CURRENT
))
3067 LOG(1, 0, 0, 0, "Locking pages into memory\n");
3069 LOG(0, 0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3074 // Drop privileges here
3075 if (config
->target_uid
> 0 && geteuid() == 0)
3076 setuid(config
->target_uid
);
3081 /* try to shut BGP down cleanly; with luck the sockets will be
3082 writable since we're out of the select */
3085 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3086 if (bgp_peers
[i
].state
== Established
)
3087 bgp_stop(&bgp_peers
[i
]);
3091 /* remove plugins (so cleanup code gets run) */
3094 // Remove the PID file if we wrote it
3095 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3096 unlink(config
->pid_file
);
3098 /* kill CLI children */
3099 signal(SIGTERM
, SIG_IGN
);
3104 void sighup_handler(int junk
)
3106 if (log_stream
&& log_stream
!= stderr
)
3115 void sigalrm_handler(int junk
)
3117 // Log current traffic stats
3119 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3120 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3121 (udp_rx
/ 1024.0 / 1024.0 * 8),
3122 (eth_tx
/ 1024.0 / 1024.0 * 8),
3123 (eth_rx
/ 1024.0 / 1024.0 * 8),
3124 (udp_tx
/ 1024.0 / 1024.0 * 8),
3125 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3126 udp_rx_pkt
, eth_rx_pkt
);
3128 udp_tx
= udp_rx
= 0;
3129 udp_rx_pkt
= eth_rx_pkt
= 0;
3130 eth_tx
= eth_rx
= 0;
3132 if (config
->dump_speed
)
3133 printf("%s\n", config
->bandwidth
);
3135 // Update the internal time counter
3137 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3142 struct param_timer p
= { time_now
};
3143 run_plugins(PLUGIN_TIMER
, &p
);
3148 void sigterm_handler(int junk
)
3150 LOG(1, 0, 0, 0, "Shutting down cleanly\n");
3151 if (config
->save_state
)
3157 void sigquit_handler(int junk
)
3161 LOG(1, 0, 0, 0, "Shutting down without saving sessions\n");
3162 for (i
= 1; i
< MAXSESSION
; i
++)
3164 if (session
[i
].opened
)
3165 sessionkill(i
, "L2TPNS Closing");
3167 for (i
= 1; i
< MAXTUNNEL
; i
++)
3169 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3170 tunnelshutdown(i
, "L2TPNS Closing");
3176 void sigchild_handler(int signal
)
3178 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3188 char magic
[sizeof(DUMP_MAGIC
) - 1];
3191 if (!config
->save_state
)
3197 if (stat(STATEFILE
, &sb
) < 0)
3203 if (sb
.st_mtime
< (time(NULL
) - 60))
3205 LOG(0, 0, 0, 0, "State file is too old to read, ignoring\n");
3210 f
= fopen(STATEFILE
, "r");
3215 LOG(0, 0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3219 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3221 LOG(0, 0, 0, 0, "Bad state file magic\n");
3225 LOG(1, 0, 0, 0, "Reading state information\n");
3226 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3228 LOG(0, 0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3232 if (buf
[0] > ip_pool_size
)
3234 LOG(0, 0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3238 LOG(2, 0, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3239 for (i
= 0; i
< buf
[0]; i
++)
3241 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3243 LOG(0, 0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3247 if (itmp
.address
!= ip_address_pool
[i
].address
)
3249 LOG(0, 0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3253 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3256 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3258 LOG(0, 0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3262 LOG(2, 0, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3263 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3265 LOG(0, 0, 0, 0, "Error reading tunnel data from state file\n");
3269 for (i
= 0; i
< MAXTUNNEL
; i
++)
3271 tunnel
[i
].controlc
= 0;
3272 tunnel
[i
].controls
= NULL
;
3273 tunnel
[i
].controle
= NULL
;
3274 if (*tunnel
[i
].hostname
)
3275 LOG(3, 0, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3278 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3280 LOG(0, 0, 0, 0, "Error/mismatch reading session header from state file\n");
3284 LOG(2, 0, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3285 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3287 LOG(0, 0, 0, 0, "Error reading session data from state file\n");
3291 for (i
= 0; i
< MAXSESSION
; i
++)
3293 session
[i
].tbf_in
= 0;
3294 session
[i
].tbf_out
= 0;
3295 if (session
[i
].opened
)
3297 LOG(2, 0, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3299 sessionsetup(session
[i
].tunnel
, i
);
3304 LOG(0, 0, 0, 0, "Loaded saved state information\n");
3312 if (!config
->save_state
)
3317 if (!(f
= fopen(STATEFILE
, "w")))
3320 LOG(1, 0, 0, 0, "Dumping state information\n");
3322 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3325 LOG(2, 0, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3326 buf
[0] = ip_pool_size
;
3327 buf
[1] = sizeof(ippoolt
);
3328 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3330 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3333 LOG(2, 0, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3335 buf
[1] = sizeof(tunnelt
);
3336 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3338 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3341 LOG(2, 0, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3342 buf
[0] = MAXSESSION
;
3343 buf
[1] = sizeof(sessiont
);
3344 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3346 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3354 LOG(0, 0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3358 void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
)
3361 *challenge_response
= NULL
;
3363 if (!*config
->l2tpsecret
)
3365 LOG(0, 0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3369 LOG(4, 0, 0, 0, " Building challenge response for CHAP request\n");
3371 *challenge_response
= (char *)calloc(17, 1);
3374 MD5Update(&ctx
, &id
, 1);
3375 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3376 MD5Update(&ctx
, challenge
, challenge_length
);
3377 MD5Final(*challenge_response
, &ctx
);
3382 static int facility_value(char *name
)
3385 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3387 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3388 return facilitynames
[i
].c_val
;
3393 void update_config()
3396 static int timeout
= 0;
3397 static int interval
= 0;
3407 if (*config
->log_filename
)
3409 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3411 char *p
= config
->log_filename
+ 7;
3414 openlog("l2tpns", LOG_PID
, facility_value(p
));
3418 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3420 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3422 fseek(log_stream
, 0, SEEK_END
);
3423 setbuf(log_stream
, NULL
);
3427 log_stream
= stderr
;
3428 setbuf(log_stream
, NULL
);
3434 log_stream
= stderr
;
3435 setbuf(log_stream
, NULL
);
3440 config
->numradiusservers
= 0;
3441 for (i
= 0; i
< MAXRADSERVER
; i
++)
3442 if (config
->radiusserver
[i
])
3444 config
->numradiusservers
++;
3445 // Set radius port: if not set, take the port from the
3446 // first radius server. For the first radius server,
3447 // take the #defined default value from l2tpns.h
3449 // test twice, In case someone works with
3450 // a secondary radius server without defining
3451 // a primary one, this will work even then.
3452 if (i
>0 && !config
->radiusport
[i
])
3453 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3454 if (!config
->radiusport
[i
])
3455 config
->radiusport
[i
] = RADPORT
;
3458 if (!config
->numradiusservers
)
3460 LOG(0, 0, 0, 0, "No RADIUS servers defined!\n");
3463 config
->num_radfds
= 2 << RADIUS_SHIFT
;
3466 for (i
= 0; i
< MAXPLUGINS
; i
++)
3468 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3470 if (*config
->plugins
[i
])
3473 add_plugin(config
->plugins
[i
]);
3475 else if (*config
->old_plugins
[i
])
3478 remove_plugin(config
->old_plugins
[i
]);
3481 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3482 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
3483 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3484 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3485 if (!*config
->cluster_interface
)
3486 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3488 if (!config
->cluster_hb_interval
)
3489 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3491 if (!config
->cluster_hb_timeout
)
3492 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3494 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3496 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3497 // late, ensure we're sufficiently larger than that
3498 int t
= 4 * config
->cluster_hb_interval
+ 11;
3500 if (config
->cluster_hb_timeout
< t
)
3502 LOG(0,0,0,0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3503 config
->cluster_hb_timeout
= t
;
3506 // Push timing changes to the slaves immediately if we're the master
3507 if (config
->cluster_iam_master
)
3508 cluster_heartbeat();
3510 interval
= config
->cluster_hb_interval
;
3511 timeout
= config
->cluster_hb_timeout
;
3515 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3518 if ((f
= fopen(config
->pid_file
, "w")))
3520 fprintf(f
, "%d\n", getpid());
3522 config
->wrote_pid
= 1;
3526 LOG(0, 0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3530 config
->reload_config
= 0;
3533 void read_config_file()
3537 if (!config
->config_file
) return;
3538 if (!(f
= fopen(config
->config_file
, "r")))
3540 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3544 LOG(3, 0, 0, 0, "Reading config file %s\n", config
->config_file
);
3546 LOG(3, 0, 0, 0, "Done reading config file\n");
3551 int sessionsetup(tunnelidt t
, sessionidt s
)
3553 // A session now exists, set it up
3559 CSTAT(call_sessionsetup
);
3561 LOG(3, session
[s
].ip
, s
, t
, "Doing session setup for session\n");
3563 if (!session
[s
].ip
|| session
[s
].ip
== 0xFFFFFFFE)
3565 assign_ip_address(s
);
3568 LOG(0, 0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3569 sessionshutdown(s
, "No IP addresses available");
3572 LOG(3, 0, s
, t
, " No IP allocated. Assigned %s from pool\n",
3573 inet_toa(htonl(session
[s
].ip
)));
3577 // Make sure this is right
3578 session
[s
].tunnel
= t
;
3580 // zap old sessions with same IP and/or username
3581 // Don't kill gardened sessions - doing so leads to a DoS
3582 // from someone who doesn't need to know the password
3585 user
= session
[s
].user
;
3586 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3588 if (i
== s
) continue;
3589 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3590 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3591 sessionkill(i
, "Duplicate session for users");
3595 // Add the route for this session.
3597 // Static IPs need to be routed. Anything else
3598 // is part of the IP address pool and is already routed,
3599 // it just needs to be added to the IP cache.
3600 if (session
[s
].ip_pool_index
== -1) // static ip
3601 routeset(s
, session
[s
].ip
, 0, 0, 1);
3603 cache_ipmap(session
[s
].ip
, s
);
3605 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3606 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, session
[s
].ip
, 1);
3608 if (!session
[s
].unique_id
)
3610 // did this session just finish radius?
3611 LOG(3, session
[s
].ip
, s
, t
, "Sending initial IPCP to client\n");
3613 session
[s
].unique_id
= ++last_id
;
3616 // Run the plugin's against this new session.
3618 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3619 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3622 // Allocate TBFs if throttled
3623 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3624 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3626 session
[s
].last_packet
= time_now
;
3629 char *sessionip
, *tunnelip
;
3630 sessionip
= strdup(inet_toa(htonl(session
[s
].ip
)));
3631 tunnelip
= strdup(inet_toa(htonl(tunnel
[t
].ip
)));
3632 LOG(2, session
[s
].ip
, s
, t
, "Login by %s at %s from %s (%s)\n",
3633 session
[s
].user
, sessionip
, tunnelip
, tunnel
[t
].hostname
);
3634 if (sessionip
) free(sessionip
);
3635 if (tunnelip
) free(tunnelip
);
3638 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3640 return 1; // RADIUS OK and IP allocated, done...
3644 // This session just got dropped on us by the master or something.
3645 // Make sure our tables up up to date...
3647 int load_session(sessionidt s
, sessiont
*new)
3652 if (new->ip_pool_index
>= MAXIPPOOL
||
3653 new->tunnel
>= MAXTUNNEL
)
3655 LOG(0,0,s
,0, "Strange session update received!\n");
3656 // FIXME! What to do here?
3661 // Ok. All sanity checks passed. Now we're committed to
3662 // loading the new session.
3665 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3668 if (new->ip
!= session
[s
].ip
) // Changed ip. fix up hash tables.
3670 if (session
[s
].ip
) // If there's an old one, remove it.
3672 // Remove any routes if the IP has changed
3673 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3675 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, session
[s
].ip
, 0);
3676 session
[s
].route
[i
].ip
= 0;
3679 if (session
[s
].ip_pool_index
== -1) // static IP
3680 routeset(s
, session
[s
].ip
, 0, 0, 0);
3681 else // It's part of the IP pool, remove it manually.
3682 uncache_ipmap(session
[s
].ip
);
3687 // If there's a new one, add it.
3688 if (new->ip_pool_index
== -1)
3689 routeset(s
, new->ip
, 0, 0, 1);
3691 cache_ipmap(new->ip
, s
);
3695 // Update routed networks
3696 for (i
= 0; i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3698 if (new->route
[i
].ip
== session
[s
].route
[i
].ip
&&
3699 new->route
[i
].mask
== session
[s
].route
[i
].mask
)
3702 if (session
[s
].route
[i
].ip
) // Remove the old one if it exists.
3703 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, session
[s
].ip
, 0);
3705 if (new->route
[i
].ip
) // Add the new one if it exists.
3706 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, new->ip
, 1);
3709 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
3710 // for walking the sessions to forward byte counts to the master.
3711 config
->cluster_highest_sessionid
= s
;
3713 // TEMP: old session struct used a u32 to define the throttle
3714 // speed for both up/down, new uses a u16 for each. Deal with
3715 // sessions from an old master for migration.
3716 if (new->throttle_out
== 0 && new->tbf_out
)
3717 new->throttle_out
= new->throttle_in
;
3719 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
3721 // Do fixups into address pool.
3722 if (new->ip_pool_index
!= -1)
3723 fix_address_pool(s
);
3729 void ringbuffer_dump(FILE *stream
)
3731 int i
= ringbuffer
->head
;
3733 while (i
!= ringbuffer
->tail
)
3735 if (*ringbuffer
->buffer
[i
].message
)
3736 fprintf(stream
, "%d-%s", ringbuffer
->buffer
[i
].level
, ringbuffer
->buffer
[i
].message
);
3737 if (++i
== ringbuffer
->tail
) break;
3738 if (i
== RINGBUFFER_SIZE
) i
= 0;
3747 loaded_plugins
= ll_init();
3748 // Initialize the plugins to nothing
3749 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
3750 plugins
[i
] = ll_init();
3753 static void *open_plugin(char *plugin_name
, int load
)
3755 char path
[256] = "";
3757 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
3758 LOG(2, 0, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
3759 return dlopen(path
, RTLD_NOW
);
3762 void add_plugin(char *plugin_name
)
3764 static struct pluginfuncs funcs
= {
3769 sessiontbysessionidt
,
3770 sessionidtbysessiont
,
3776 void *p
= open_plugin(plugin_name
, 1);
3777 int (*initfunc
)(struct pluginfuncs
*);
3782 LOG(1, 0, 0, 0, " Plugin load failed: %s\n", dlerror());
3786 if (ll_contains(loaded_plugins
, p
))
3793 int *v
= dlsym(p
, "__plugin_api_version");
3794 if (!v
|| *v
!= PLUGIN_API_VERSION
)
3796 LOG(1, 0, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
3802 if ((initfunc
= dlsym(p
, "plugin_init")))
3804 if (!initfunc(&funcs
))
3806 LOG(1, 0, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
3812 ll_push(loaded_plugins
, p
);
3814 for (i
= 0; i
< max_plugin_functions
; i
++)
3817 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3819 LOG(3, 0, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
3820 ll_push(plugins
[i
], x
);
3824 LOG(2, 0, 0, 0, " Loaded plugin %s\n", plugin_name
);
3827 static void run_plugin_done(void *plugin
)
3829 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
3835 void remove_plugin(char *plugin_name
)
3837 void *p
= open_plugin(plugin_name
, 0);
3843 for (i
= 0; i
< max_plugin_functions
; i
++)
3846 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3847 ll_delete(plugins
[i
], x
);
3850 if (ll_contains(loaded_plugins
, p
))
3852 ll_delete(loaded_plugins
, p
);
3857 LOG(2, 0, 0, 0, "Removed plugin %s\n", plugin_name
);
3860 int run_plugins(int plugin_type
, void *data
)
3862 int (*func
)(void *data
);
3863 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
) return 1;
3865 ll_reset(plugins
[plugin_type
]);
3866 while ((func
= ll_next(plugins
[plugin_type
])))
3870 if (rc
== PLUGIN_RET_STOP
) return 1;
3871 if (rc
== PLUGIN_RET_ERROR
) return 0;
3880 ll_reset(loaded_plugins
);
3881 while ((p
= ll_next(loaded_plugins
)))
3885 void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
)
3889 struct param_control param
= { buf
, len
, ntohl(addr
->sin_addr
.s_addr
), ntohs(addr
->sin_port
), NULL
, 0, 0 };
3892 if (log_stream
&& config
->debug
>= 4)
3894 LOG(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Received ");
3895 dump_packet(buf
, log_stream
);
3898 resp
= calloc(1400, 1);
3899 l
= new_packet(PKT_RESP_ERROR
, resp
);
3900 *(int *)(resp
+ 6) = *(int *)(buf
+ 6);
3902 param
.type
= ntohs(*(short *)(buf
+ 2));
3903 param
.id
= ntohl(*(int *)(buf
+ 6));
3904 param
.data_length
= ntohs(*(short *)(buf
+ 4)) - 10;
3905 param
.data
= (param
.data_length
> 0) ? (char *)(buf
+ 10) : NULL
;
3906 param
.response
= resp
;
3907 param
.response_length
= l
;
3909 run_plugins(PLUGIN_CONTROL
, ¶m
);
3911 if (param
.send_response
)
3913 send_packet(controlfd
, ntohl(addr
->sin_addr
.s_addr
), ntohs(addr
->sin_port
), param
.response
, param
.response_length
);
3914 LOG(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Sent Control packet response\n");
3922 * Go through all of the tunnels and do some cleanups
3928 LOG(1, 0, 0, 0, "Cleaning tunnels array\n");
3930 for (i
= 1; i
< MAXTUNNEL
; i
++)
3933 || !*tunnel
[i
].hostname
3934 || (tunnel
[i
].state
== TUNNELDIE
&& tunnel
[i
].die
>= time_now
))
3941 void tunnelclear(tunnelidt t
)
3944 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
3945 tunnel
[t
].state
= TUNNELFREE
;
3948 tunnelidt
new_tunnel()
3951 for (i
= 1; i
< MAXTUNNEL
; i
++)
3953 if (tunnel
[i
].state
== TUNNELFREE
)
3955 LOG(4, 0, 0, i
, "Assigning tunnel ID %d\n", i
);
3956 if (i
> config
->cluster_highest_tunnelid
)
3957 config
->cluster_highest_tunnelid
= i
;
3961 LOG(0, 0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
3966 // We're becoming the master. Do any required setup..
3968 // This is principally telling all the plugins that we're
3969 // now a master, and telling them about all the sessions
3970 // that are active too..
3972 void become_master(void)
3975 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
3977 // running a bunch of iptables commands is slow and can cause
3978 // the master to drop tunnels on takeover--kludge around the
3979 // problem by forking for the moment (note: race)
3980 if (!fork_and_close())
3982 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
3984 if (!session
[s
].tunnel
) // Not an in-use session.
3987 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
3993 for (i
= 0; i
< config
->num_radfds
; i
++)
3995 if (!radfds
[i
]) continue;
3996 FD_SET(radfds
[i
], &readset
);
3997 if (radfds
[i
] > readset_n
)
3998 readset_n
= radfds
[i
];
4002 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4008 if (CLI_HELP_REQUESTED
)
4009 return CLI_HELP_NO_ARGS
;
4012 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4014 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4017 if (!session
[s
].tunnel
)
4020 idle
= time_now
- session
[s
].last_packet
;
4021 idle
/= 5 ; // In multiples of 5 seconds.
4031 for (i
= 0; i
< 63; ++i
)
4033 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4035 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4036 cli_print(cli
, "%d total sessions open.", count
);
4040 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4046 if (CLI_HELP_REQUESTED
)
4047 return CLI_HELP_NO_ARGS
;
4050 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4052 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4055 if (!session
[s
].tunnel
)
4058 d
= time_now
- session
[s
].opened
;
4061 while (d
> 1 && open
< 32)
4071 for (i
= 0; i
< 30; ++i
)
4073 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4076 cli_print(cli
, "%d total sessions open.", count
);
4082 * This unencodes the AVP using the L2TP CHAP secret and the
4083 * previously stored random vector. It replaces the hidden data with
4084 * the cleartext data and returns the length of the cleartext data
4085 * (including the AVP "header" of 6 bytes).
4087 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4089 int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
)
4094 u8 working_vector
[16];
4095 uint16_t hidden_length
;
4100 // Find the AVP type.
4101 type
[0] = *(avp
+ 4);
4102 type
[1] = *(avp
+ 5);
4104 // Line up with the hidden data
4105 cursor
= output
= avp
+ 6;
4107 // Compute initial pad
4109 MD5Update(&ctx
, type
, 2);
4110 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4111 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4112 MD5Final(digest
, &ctx
);
4114 // Get hidden length
4115 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4117 // Keep these for later use
4118 working_vector
[0] = *cursor
;
4119 working_vector
[1] = *(cursor
+ 1);
4122 if (hidden_length
> length
- 8)
4124 LOG(1, 0, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4128 /* Decrypt remainder */
4130 todo
= hidden_length
;
4133 working_vector
[done
] = *cursor
;
4134 *output
= digest
[done
] ^ *cursor
;
4139 if (done
== 16 && todo
)
4141 // Compute new digest
4144 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4145 MD5Update(&ctx
, &working_vector
, 16);
4146 MD5Final(digest
, &ctx
);
4150 return hidden_length
+ 6;