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.57 2004/11/27 05:19:53 bodea Exp $";
13 #include <linux/if_tun.h>
18 #include <net/route.h>
21 #include <netinet/in.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
31 #include <sys/resource.h>
39 #include <sys/sysinfo.h>
47 #include "constants.h"
57 configt
*config
= NULL
; // all configuration
58 int tunfd
= -1; // tun interface file handle. (network device)
59 int udpfd
= -1; // UDP file handle
60 int controlfd
= -1; // Control signal handle
61 int clifd
= -1; // Socket listening for CLI connections.
62 int snoopfd
= -1; // UDP file handle for sending out intercept data
63 int *radfds
= NULL
; // RADIUS requests file handles
64 int ifrfd
= -1; // File descriptor for routing, etc
65 time_t basetime
= 0; // base clock
66 char hostname
[1000] = ""; // us.
67 static u32 sessionid
= 0; // session id for radius accounting
68 static int syslog_log
= 0; // are we logging to syslog
69 static FILE *log_stream
= NULL
; // file handle for direct logging (i.e. direct into file, not via syslog).
70 extern int cluster_sockfd
; // Intra-cluster communications socket.
71 u32 last_id
= 0; // Last used PPP SID. Can I kill this?? -- mo
73 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
74 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
76 static void *ip_hash
[256]; // Mapping from IP address to session structures.
79 static u32 udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
80 static u32 eth_rx
= 0, eth_rx_pkt
= 0;
83 static u32 ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
84 time_t time_now
= 0; // Current time in seconds since epoch.
85 static char time_now_string
[64] = {0}; // Current time as a string.
86 static char main_quit
= 0; // True if we're in the process of exiting.
87 linked_list
*loaded_plugins
;
88 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
90 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
91 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
93 config_descriptt config_values
[] = {
94 CONFIG("debug", debug
, INT
),
95 CONFIG("log_file", log_filename
, STRING
),
96 CONFIG("pid_file", pid_file
, STRING
),
97 CONFIG("l2tp_secret", l2tpsecret
, STRING
),
98 CONFIG("primary_dns", default_dns1
, IP
),
99 CONFIG("secondary_dns", default_dns2
, IP
),
100 CONFIG("save_state", save_state
, BOOL
),
101 CONFIG("primary_radius", radiusserver
[0], IP
),
102 CONFIG("secondary_radius", radiusserver
[1], IP
),
103 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
104 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
105 CONFIG("radius_accounting", radius_accounting
, BOOL
),
106 CONFIG("radius_secret", radiussecret
, STRING
),
107 CONFIG("bind_address", bind_address
, IP
),
108 CONFIG("peer_address", peer_address
, IP
),
109 CONFIG("send_garp", send_garp
, BOOL
),
110 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
111 CONFIG("throttle_buckets", num_tbfs
, INT
),
112 CONFIG("accounting_dir", accounting_dir
, STRING
),
113 CONFIG("setuid", target_uid
, INT
),
114 CONFIG("dump_speed", dump_speed
, BOOL
),
115 CONFIG("cleanup_interval", cleanup_interval
, INT
),
116 CONFIG("multi_read_count", multi_read_count
, INT
),
117 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
118 CONFIG("lock_pages", lock_pages
, BOOL
),
119 CONFIG("icmp_rate", icmp_rate
, INT
),
120 CONFIG("cluster_address", cluster_address
, IP
),
121 CONFIG("cluster_interface", cluster_interface
, STRING
),
122 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
123 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
127 static char *plugin_functions
[] = {
134 "plugin_new_session",
135 "plugin_kill_session",
137 "plugin_radius_response",
138 "plugin_become_master",
139 "plugin_new_session_master",
142 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
144 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
145 sessiont
*session
= NULL
; // Array of session structures.
146 sessioncountt
*sess_count
= NULL
; // Array of partial per-session traffic counters.
147 radiust
*radius
= NULL
; // Array of radius structures.
148 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
149 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
150 static controlt
*controlfree
= 0;
151 struct Tstats
*_statistics
= NULL
;
153 struct Tringbuffer
*ringbuffer
= NULL
;
156 static void cache_ipmap(ipt ip
, int s
);
157 static void uncache_ipmap(ipt ip
);
158 static void free_ip_address(sessionidt s
);
159 static void dump_acct_info(void);
160 static void sighup_handler(int sig
);
161 static void sigalrm_handler(int sig
);
162 static void sigterm_handler(int sig
);
163 static void sigquit_handler(int sig
);
164 static void sigchild_handler(int sig
);
165 static void read_state(void);
166 static void dump_state(void);
167 static void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
);
168 static void update_config(void);
169 static void read_config_file(void);
170 static void initplugins(void);
171 static int add_plugin(char *plugin_name
);
172 static int remove_plugin(char *plugin_name
);
173 static void plugins_done(void);
174 static void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
, int alen
);
175 static tunnelidt
new_tunnel(void);
176 static int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
);
178 // return internal time (10ths since process startup)
179 static clockt
now(void)
183 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
186 // work out a retry time based on try number
187 // This is a straight bounded exponential backoff.
188 // Maximum re-try time is 32 seconds. (2^5).
189 clockt
backoff(u8
try)
191 if (try > 5) try = 5; // max backoff
192 return now() + 10 * (1 << try);
197 // Log a debug message. Typically called vias LOG macro
199 void _log(int level
, ipt address
, sessionidt s
, tunnelidt t
, const char *format
, ...)
201 static char message
[65536] = {0};
202 static char message2
[65536] = {0};
208 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
209 ringbuffer
->tail
= 0;
210 if (ringbuffer
->tail
== ringbuffer
->head
)
211 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
212 ringbuffer
->head
= 0;
214 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
215 ringbuffer
->buffer
[ringbuffer
->tail
].address
= address
;
216 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
217 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
218 va_start(ap
, format
);
219 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
224 if (config
->debug
< level
) return;
226 va_start(ap
, format
);
229 vsnprintf(message2
, 65535, format
, ap
);
230 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
231 fprintf(log_stream
, "%s", message
);
235 vsnprintf(message2
, 65535, format
, ap
);
236 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
237 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
242 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
245 const u8
*d
= (const u8
*)data
;
247 if (config
->debug
< level
) return;
249 // No support for _log_hex to syslog
252 _log(level
, 0, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
253 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
255 for (i
= 0; i
< maxsize
; )
257 fprintf(log_stream
, "%4X: ", i
);
258 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
260 fprintf(log_stream
, "%02X ", d
[j
]);
262 fputs(": ", log_stream
);
265 for (; j
< i
+ 16; j
++)
267 fputs(" ", log_stream
);
269 fputs(": ", log_stream
);
272 fputs(" ", log_stream
);
273 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
275 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
276 fputc(d
[j
], log_stream
);
278 fputc('.', log_stream
);
281 fputs(" ", log_stream
);
285 fputs("\n", log_stream
);
289 setbuf(log_stream
, NULL
);
296 // This adds it to the routing table, advertises it
297 // via BGP if enabled, and stuffs it into the
298 // 'sessionbyip' cache.
300 // 'ip' and 'mask' must be in _host_ order.
302 static void routeset(sessionidt s
, ipt ip
, ipt mask
, ipt gw
, u8 add
)
307 if (!mask
) mask
= 0xffffffff;
309 ip
&= mask
; // Force the ip to be the first one in the route.
311 memset(&r
, 0, sizeof(r
));
312 r
.rt_dev
= config
->tundevice
;
313 r
.rt_dst
.sa_family
= AF_INET
;
314 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
315 r
.rt_gateway
.sa_family
= AF_INET
;
316 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
317 r
.rt_genmask
.sa_family
= AF_INET
;
318 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
319 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
321 r
.rt_flags
|= RTF_GATEWAY
;
322 else if (mask
== 0xffffffff)
323 r
.rt_flags
|= RTF_HOST
;
325 LOG(1, ip
, 0, 0, "Route %s %u.%u.%u.%u/%u.%u.%u.%u %u.%u.%u.%u\n",
327 ip
>> 24, ip
>> 16 & 0xff, ip
>> 8 & 0xff, ip
& 0xff,
328 mask
>> 24, mask
>> 16 & 0xff, mask
>> 8 & 0xff, mask
& 0xff,
329 gw
>> 24, gw
>> 16 & 0xff, gw
>> 8 & 0xff, gw
& 0xff);
331 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
332 LOG(0, 0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
336 bgp_add_route(htonl(ip
), htonl(mask
));
338 bgp_del_route(htonl(ip
), htonl(mask
));
341 // Add/Remove the IPs to the 'sessionbyip' cache.
342 // Note that we add the zero address in the case of
343 // a network route. Roll on CIDR.
345 // Note that 's == 0' implies this is the address pool.
346 // We still cache it here, because it will pre-fill
347 // the malloc'ed tree.
351 if (!add
) // Are we deleting a route?
352 s
= 0; // Caching the session as '0' is the same as uncaching.
354 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
360 // Set up TUN interface
361 static void inittun(void)
364 struct sockaddr_in sin
= {0};
365 memset(&ifr
, 0, sizeof(ifr
));
366 ifr
.ifr_flags
= IFF_TUN
;
368 tunfd
= open(TUNDEVICE
, O_RDWR
);
371 LOG(0, 0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
375 int flags
= fcntl(tunfd
, F_GETFL
, 0);
376 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
378 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
380 LOG(0, 0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
383 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
384 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
385 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
387 sin
.sin_family
= AF_INET
;
388 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
389 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
391 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
393 LOG(0, 0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
396 /* Bump up the qlen to deal with bursts from the network */
398 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
400 LOG(0, 0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
403 ifr
.ifr_flags
= IFF_UP
;
404 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
406 LOG(0, 0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
412 static void initudp(void)
415 struct sockaddr_in addr
;
418 memset(&addr
, 0, sizeof(addr
));
419 addr
.sin_family
= AF_INET
;
420 addr
.sin_port
= htons(L2TPPORT
);
421 addr
.sin_addr
.s_addr
= config
->bind_address
;
422 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
423 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
425 int flags
= fcntl(udpfd
, F_GETFL
, 0);
426 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
428 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
430 LOG(0, 0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
433 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
436 memset(&addr
, 0, sizeof(addr
));
437 addr
.sin_family
= AF_INET
;
438 addr
.sin_port
= htons(NSCTL_PORT
);
439 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
440 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
441 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
443 LOG(0, 0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
449 // Find session by IP, < 1 for not found
451 // Confusingly enough, this 'ip' must be
452 // in _network_ order. This being the common
453 // case when looking it up from IP packet headers.
455 // We actually use this cache for two things.
456 // #1. For used IP addresses, this maps to the
457 // session ID that it's used by.
458 // #2. For un-used IP addresses, this maps to the
459 // index into the pool table that contains that
463 static int lookup_ipmap(ipt ip
)
466 char **d
= (char **) ip_hash
;
469 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
470 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
471 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
473 s
= (ipt
) d
[(size_t) *a
];
477 sessionidt
sessionbyip(ipt ip
)
479 int s
= lookup_ipmap(ip
);
480 CSTAT(call_sessionbyip
);
482 if (s
> 0 && s
< MAXSESSION
&& session
[s
].tunnel
)
488 // Take an IP address in HOST byte order and
489 // add it to the sessionid by IP cache.
491 // (It's actually cached in network order)
493 static void cache_ipmap(ipt ip
, int s
)
495 ipt nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char*)(&ip))[0]
497 char **d
= (char **) ip_hash
;
500 for (i
= 0; i
< 3; i
++)
502 if (!d
[(size_t) a
[i
]])
504 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof (void *))))
508 d
= (char **) d
[(size_t) a
[i
]];
511 d
[(size_t) a
[3]] = (char *)((int)s
);
514 LOG(4, ip
, s
, session
[s
].tunnel
, "Caching ip address %s\n", inet_toa(nip
));
516 LOG(4, ip
, 0, 0, "Un-caching ip address %s\n", inet_toa(nip
));
517 // else a map to an ip pool index.
520 static void uncache_ipmap(ipt ip
)
522 cache_ipmap(ip
, 0); // Assign it to the NULL session.
526 // CLI list to dump current ipcache.
528 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
530 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
534 if (CLI_HELP_REQUESTED
)
535 return CLI_HELP_NO_ARGS
;
537 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
539 for (i
= 0; i
< 256; ++i
)
544 for (j
= 0; j
< 256; ++j
)
549 for (k
= 0; k
< 256; ++k
)
554 for (l
= 0; l
< 256; ++l
)
558 cli_print(cli
, "%7d %d.%d.%d.%d", (int) g
[l
], i
, j
, k
, l
);
564 cli_print(cli
, "%d entries in cache", count
);
569 // Find session by username, 0 for not found
570 // walled garden users aren't authenticated, so the username is
571 // reasonably useless. Ignore them to avoid incorrect actions
573 // This is VERY inefficent. Don't call it often. :)
575 sessionidt
sessionbyuser(char *username
)
578 CSTAT(call_sessionbyuser
);
580 for (s
= 1; s
< MAXSESSION
; ++s
)
582 if (session
[s
].walled_garden
)
583 continue; // Skip walled garden users.
585 if (!strncmp(session
[s
].user
, username
, 128))
589 return 0; // Not found.
592 void send_garp(ipt ip
)
598 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
601 LOG(0, 0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
604 memset(&ifr
, 0, sizeof(ifr
));
605 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
606 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
608 LOG(0, 0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
612 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
613 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
615 LOG(0, 0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
620 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
623 // Find session by username, 0 for not found
624 static sessiont
*sessiontbysessionidt(sessionidt s
)
626 if (!s
|| s
> MAXSESSION
) return NULL
;
630 static sessionidt
sessionidtbysessiont(sessiont
*s
)
632 sessionidt val
= s
-session
;
633 if (s
< session
|| val
> MAXSESSION
) return 0;
637 // actually send a control message for a specific tunnel
638 void tunnelsend(u8
* buf
, u16 l
, tunnelidt t
)
640 struct sockaddr_in addr
;
642 CSTAT(call_tunnelsend
);
646 static int backtrace_count
= 0;
647 LOG(0, 0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
648 STAT(tunnel_tx_errors
);
649 log_backtrace(backtrace_count
, 5)
655 static int backtrace_count
= 0;
656 LOG(1, 0, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
657 log_backtrace(backtrace_count
, 5)
658 STAT(tunnel_tx_errors
);
662 memset(&addr
, 0, sizeof(addr
));
663 addr
.sin_family
= AF_INET
;
664 *(u32
*) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
665 addr
.sin_port
= htons(tunnel
[t
].port
);
667 // sequence expected, if sequence in message
668 if (*buf
& 0x08) *(u16
*) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
670 // If this is a control message, deal with retries
673 tunnel
[t
].last
= time_now
; // control message sent
674 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
675 if (tunnel
[t
].try > 1)
677 STAT(tunnel_retries
);
678 LOG(3, tunnel
[t
].ip
, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
682 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
684 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",
685 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
686 STAT(tunnel_tx_errors
);
690 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
691 STAT(tunnel_tx_packets
);
692 INC_STAT(tunnel_tx_bytes
, l
);
696 // Tiny helper function to write data to
699 int tun_write(u8
* data
, int size
)
701 return write(tunfd
, data
, size
);
704 // process outgoing (to tunnel) IP
706 static void processipout(u8
* buf
, int len
)
713 char * data
= buf
; // Keep a copy of the originals.
718 CSTAT(call_processipout
);
720 if (len
< MIN_IP_SIZE
)
722 LOG(1, 0, 0, 0, "Short IP, %d bytes\n", len
);
723 STAT(tunnel_tx_errors
);
728 LOG(1, 0, 0, 0, "Oversize IP packet %d bytes\n", len
);
729 STAT(tunnel_tx_errors
);
733 // Skip the tun header
737 // Got an IP header now
738 if (*(u8
*)(buf
) >> 4 != 4)
740 LOG(1, 0, 0, 0, "IP: Don't understand anything except IPv4\n");
744 ip
= *(u32
*)(buf
+ 16);
745 if (!(s
= sessionbyip(ip
)))
747 // Is this a packet for a session that doesn't exist?
748 static int rate
= 0; // Number of ICMP packets we've sent this second.
749 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
751 if (last
!= time_now
)
757 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
759 LOG(4, 0, 0, 0, "IP: Sending ICMP host unreachable to %s\n", inet_toa(*(u32
*)(buf
+ 12)));
760 host_unreachable(*(u32
*)(buf
+ 12), *(u16
*)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
764 t
= session
[s
].tunnel
;
769 // Are we throttling this session?
770 if (config
->cluster_iam_master
)
771 tbf_queue_packet(sp
->tbf_out
, data
, size
);
773 master_throttle_packet(sp
->tbf_out
, data
, size
);
776 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
778 // We are walled-gardening this
779 master_garden_packet(s
, data
, size
);
783 LOG(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
785 // Add on L2TP header
787 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
789 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
792 // Snooping this session, send it to intercept box
793 if (sp
->snoop_ip
&& sp
->snoop_port
)
794 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
796 sp
->cout
+= len
; // byte count
797 sp
->total_cout
+= len
; // byte count
800 sess_count
[s
].cout
+= len
; // To send to master..
804 // Helper routine for the TBF filters.
805 // Used to send queued data in to the user!
807 static void send_ipout(sessionidt s
, u8
*buf
, int len
)
815 if (len
< 0 || len
> MAXETHER
)
817 LOG(1,0,0,0, "Odd size IP packet: %d bytes\n", len
);
821 // Skip the tun header
825 ip
= *(u32
*)(buf
+ 16);
830 t
= session
[s
].tunnel
;
833 LOG(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
835 // Add on L2TP header
837 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
839 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
842 // Snooping this session.
843 if (sp
->snoop_ip
&& sp
->snoop_port
)
844 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
846 sp
->cout
+= len
; // byte count
847 sp
->total_cout
+= len
; // byte count
850 sess_count
[s
].cout
+= len
; // To send to master..
853 // add an AVP (16 bit)
854 static void control16(controlt
* c
, u16 avp
, u16 val
, u8 m
)
856 u16 l
= (m
? 0x8008 : 0x0008);
857 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
858 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
859 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
860 *(u16
*) (c
->buf
+ c
->length
+ 6) = htons(val
);
864 // add an AVP (32 bit)
865 static void control32(controlt
* c
, u16 avp
, u32 val
, u8 m
)
867 u16 l
= (m
? 0x800A : 0x000A);
868 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
869 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
870 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
871 *(u32
*) (c
->buf
+ c
->length
+ 6) = htonl(val
);
875 // add an AVP (32 bit)
876 static void controls(controlt
* c
, u16 avp
, char *val
, u8 m
)
878 u16 l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
879 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
880 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
881 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
882 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
883 c
->length
+= 6 + strlen(val
);
887 static void controlb(controlt
* c
, u16 avp
, char *val
, unsigned int len
, u8 m
)
889 u16 l
= ((m
? 0x8000 : 0) + len
+ 6);
890 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
891 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
892 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
893 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
894 c
->length
+= 6 + len
;
897 // new control connection
898 static controlt
*controlnew(u16 mtype
)
902 c
= malloc(sizeof(controlt
));
906 controlfree
= c
->next
;
910 *(u16
*) (c
->buf
+ 0) = htons(0xC802); // flags/ver
912 control16(c
, 0, mtype
, 1);
916 // send zero block if nothing is waiting
918 static void controlnull(tunnelidt t
)
921 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
924 *(u16
*) (buf
+ 0) = htons(0xC802); // flags/ver
925 *(u16
*) (buf
+ 2) = htons(12); // length
926 *(u16
*) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
927 *(u16
*) (buf
+ 6) = htons(0); // session
928 *(u16
*) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
929 *(u16
*) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
930 tunnelsend(buf
, 12, t
);
933 // add a control message to a tunnel, and send if within window
934 static void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
936 *(u16
*) (c
->buf
+ 2) = htons(c
->length
); // length
937 *(u16
*) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
938 *(u16
*) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
939 *(u16
*) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
940 tunnel
[t
].ns
++; // advance sequence
941 // link in message in to queue
942 if (tunnel
[t
].controlc
)
943 tunnel
[t
].controle
->next
= c
;
945 tunnel
[t
].controls
= c
;
947 tunnel
[t
].controle
= c
;
948 tunnel
[t
].controlc
++;
950 // send now if space in window
951 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
953 tunnel
[t
].try = 0; // first send
954 tunnelsend(c
->buf
, c
->length
, t
);
959 // Throttle or Unthrottle a session
961 // Throttle the data from/to through a session to no more than
962 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
965 // If either value is -1, the current value is retained for that
968 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
970 if (!session
[s
].tunnel
)
971 return; // No-one home.
973 if (!*session
[s
].user
)
974 return; // User not logged in
978 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
979 if (session
[s
].tbf_in
)
980 free_tbf(session
[s
].tbf_in
);
983 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
985 session
[s
].tbf_in
= 0;
987 session
[s
].throttle_in
= rate_in
;
992 int bytes
= rate_out
* 1024 / 8;
993 if (session
[s
].tbf_out
)
994 free_tbf(session
[s
].tbf_out
);
997 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
999 session
[s
].tbf_out
= 0;
1001 session
[s
].throttle_out
= rate_out
;
1005 // start tidy shutdown of session
1006 void sessionshutdown(sessionidt s
, char *reason
)
1008 int walled_garden
= session
[s
].walled_garden
;
1011 CSTAT(call_sessionshutdown
);
1013 if (!session
[s
].tunnel
)
1015 LOG(3, session
[s
].ip
, s
, session
[s
].tunnel
, "Called sessionshutdown on a session with no tunnel.\n");
1016 return; // not a live session
1019 if (!session
[s
].die
)
1021 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1022 LOG(2, 0, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1023 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1026 // RADIUS Stop message
1027 if (session
[s
].opened
&& !walled_garden
&& !session
[s
].die
)
1029 u16 r
= session
[s
].radius
;
1032 if (!(r
= radiusnew(s
)))
1034 LOG(1, 0, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1035 STAT(radius_overflow
);
1040 for (n
= 0; n
< 15; n
++)
1041 radius
[r
].auth
[n
] = rand();
1044 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1045 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1049 { // IP allocated, clear and unroute
1052 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1054 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1055 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1058 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1059 session
[s
].route
[r
].ip
= 0;
1062 if (session
[s
].ip_pool_index
== -1) // static ip
1064 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1071 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1072 throttle_session(s
, 0, 0);
1075 controlt
*c
= controlnew(14); // sending CDN
1076 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1077 control16(c
, 14, s
, 1); // assigned session (our end)
1078 controladd(c
, session
[s
].tunnel
, s
); // send the message
1081 if (!session
[s
].die
)
1082 session
[s
].die
= now() + 150; // Clean up in 15 seconds
1084 cluster_send_session(s
);
1087 void sendipcp(tunnelidt t
, sessionidt s
)
1090 u16 r
= session
[s
].radius
;
1093 CSTAT(call_sendipcp
);
1098 if (radius
[r
].state
!= RADIUSIPCP
)
1100 radius
[r
].state
= RADIUSIPCP
;
1104 radius
[r
].retry
= backoff(radius
[r
].try++);
1105 if (radius
[r
].try > 10)
1107 radiusclear(r
, s
); // Clear radius session.
1108 sessionshutdown(s
, "No reply on IPCP");
1112 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1116 q
[1] = r
<< RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1117 *(u16
*) (q
+ 2) = htons(10);
1120 *(u32
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1121 config
->bind_address
? config
->bind_address
:
1122 my_address
; // send my IP
1124 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1125 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1128 // kill a session now
1129 static void sessionkill(sessionidt s
, char *reason
)
1132 CSTAT(call_sessionkill
);
1134 session
[s
].die
= now();
1135 sessionshutdown(s
, reason
); // close radius/routes, etc.
1136 if (session
[s
].radius
)
1137 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1139 LOG(2, 0, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1141 memset(&session
[s
], 0, sizeof(session
[s
]));
1142 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1143 session
[s
].next
= sessionfree
;
1145 cli_session_actions
[s
].action
= 0;
1146 cluster_send_session(s
);
1149 static void tunnelclear(tunnelidt t
)
1152 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1153 tunnel
[t
].state
= TUNNELFREE
;
1156 // kill a tunnel now
1157 static void tunnelkill(tunnelidt t
, char *reason
)
1162 CSTAT(call_tunnelkill
);
1164 tunnel
[t
].state
= TUNNELDIE
;
1166 // free control messages
1167 while ((c
= tunnel
[t
].controls
))
1169 controlt
* n
= c
->next
;
1170 tunnel
[t
].controls
= n
;
1171 tunnel
[t
].controlc
--;
1172 c
->next
= controlfree
;
1176 for (s
= 1; s
< MAXSESSION
; s
++)
1177 if (session
[s
].tunnel
== t
)
1178 sessionkill(s
, reason
);
1182 LOG(1, 0, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1183 cli_tunnel_actions
[s
].action
= 0;
1184 cluster_send_tunnel(t
);
1187 // shut down a tunnel cleanly
1188 static void tunnelshutdown(tunnelidt t
, char *reason
)
1192 CSTAT(call_tunnelshutdown
);
1194 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1196 // never set up, can immediately kill
1197 tunnelkill(t
, reason
);
1200 LOG(1, 0, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1203 for (s
= 1; s
< MAXSESSION
; s
++)
1204 if (session
[s
].tunnel
== t
)
1205 sessionshutdown(s
, reason
);
1207 tunnel
[t
].state
= TUNNELDIE
;
1208 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
1209 cluster_send_tunnel(t
);
1210 // TBA - should we wait for sessions to stop?
1212 controlt
*c
= controlnew(4); // sending StopCCN
1213 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message
1214 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1215 controladd(c
, t
, 0); // send the message
1219 // read and process packet on tunnel (UDP)
1220 void processudp(u8
* buf
, int len
, struct sockaddr_in
*addr
)
1222 char *chapresponse
= NULL
;
1223 u16 l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1227 CSTAT(call_processudp
);
1231 LOG_HEX(5, "UDP Data", buf
, len
);
1232 STAT(tunnel_rx_packets
);
1233 INC_STAT(tunnel_rx_bytes
, len
);
1236 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Short UDP, %d bytes\n", len
);
1237 STAT(tunnel_rx_errors
);
1240 if ((buf
[1] & 0x0F) != 2)
1242 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1243 STAT(tunnel_rx_errors
);
1248 l
= ntohs(*(u16
*) p
);
1251 t
= ntohs(*(u16
*) p
);
1253 s
= ntohs(*(u16
*) p
);
1255 if (s
>= MAXSESSION
)
1257 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid session ID\n");
1258 STAT(tunnel_rx_errors
);
1263 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid tunnel ID\n");
1264 STAT(tunnel_rx_errors
);
1269 ns
= ntohs(*(u16
*) p
);
1271 nr
= ntohs(*(u16
*) p
);
1276 u16 o
= ntohs(*(u16
*) p
);
1281 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad length %d>%d\n", (p
- buf
), l
);
1282 STAT(tunnel_rx_errors
);
1288 u16 message
= 0xFFFF; // message type
1290 u8 mandatorymessage
= 0;
1291 u8 chap
= 0; // if CHAP being used
1292 u16 asession
= 0; // assigned session
1293 u32 amagic
= 0; // magic number
1294 u8 aflags
= 0; // flags from last LCF
1295 u16 version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1296 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1297 char called
[MAXTEL
] = ""; // called number
1298 char calling
[MAXTEL
] = ""; // calling number
1300 if (!config
->cluster_iam_master
)
1302 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1306 if ((*buf
& 0xCA) != 0xC8)
1308 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad control header %02X\n", *buf
);
1309 STAT(tunnel_rx_errors
);
1313 // check for duplicate tunnel open message
1319 // Is this a duplicate of the first packet? (SCCRQ)
1321 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1323 if (tunnel
[i
].state
!= TUNNELOPENING
||
1324 tunnel
[i
].ip
!= ntohl(*(ipt
*) & addr
->sin_addr
) ||
1325 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1328 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Duplicate SCCRQ?\n");
1333 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",
1334 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1336 // if no tunnel specified, assign one
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 STAT(tunnel_created
);
1350 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, t
, " New tunnel from %u.%u.%u.%u/%u ID %d\n",
1351 tunnel
[t
].ip
>> 24, tunnel
[t
].ip
>> 16 & 255,
1352 tunnel
[t
].ip
>> 8 & 255, tunnel
[t
].ip
& 255, tunnel
[t
].port
, t
);
1355 // If the 'ns' just received is not the 'nr' we're
1356 // expecting, just send an ack and drop it.
1358 // if 'ns' is less, then we got a retransmitted packet.
1359 // if 'ns' is greater than missed a packet. Either way
1360 // we should ignore it.
1361 if (ns
!= tunnel
[t
].nr
)
1363 // is this the sequence we were expecting?
1364 STAT(tunnel_rx_errors
);
1365 LOG(1, ntohl(addr
->sin_addr
.s_addr
), 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n",
1366 t
, ns
, tunnel
[t
].nr
);
1368 if (l
) // Is this not a ZLB?
1373 // This is used to time out old tunnels
1374 tunnel
[t
].lastrec
= time_now
;
1376 // check sequence of this message
1378 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1379 // some to clear maybe?
1380 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1382 controlt
*c
= tunnel
[t
].controls
;
1383 tunnel
[t
].controls
= c
->next
;
1384 tunnel
[t
].controlc
--;
1385 c
->next
= controlfree
;
1388 tunnel
[t
].try = 0; // we have progress
1391 // receiver advance (do here so quoted correctly in any sends below)
1392 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1393 if (skip
< 0) skip
= 0;
1394 if (skip
< tunnel
[t
].controlc
)
1396 // some control packets can now be sent that were previous stuck out of window
1397 int tosend
= tunnel
[t
].window
- skip
;
1398 controlt
*c
= tunnel
[t
].controls
;
1406 tunnel
[t
].try = 0; // first send
1407 tunnelsend(c
->buf
, c
->length
, t
);
1412 if (!tunnel
[t
].controlc
)
1413 tunnel
[t
].retry
= 0; // caught up
1416 { // if not a null message
1418 while (l
&& !(fatal
& 0x80))
1420 u16 n
= (ntohs(*(u16
*) p
) & 0x3FF);
1427 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Invalid length in AVP\n");
1428 STAT(tunnel_rx_errors
);
1435 // handle hidden AVPs
1436 if (!*config
->l2tpsecret
)
1438 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1442 if (!session
[s
].random_vector_length
)
1444 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no random vector.\n");
1448 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP\n");
1450 n
= unhide_avp(b
, t
, s
, n
);
1459 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1466 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown AVP vendor %d\n", ntohs(*(u16
*) (b
)));
1471 mtype
= ntohs(*(u16
*) (b
));
1475 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1478 case 0: // message type
1479 message
= ntohs(*(u16
*) b
);
1480 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Message type = %d (%s)\n", *b
,
1481 l2tp_message_types
[message
]);
1482 mandatorymessage
= flags
;
1484 case 1: // result code
1486 u16 rescode
= ntohs(*(u16
*)(b
));
1487 const char* resdesc
= "(unknown)";
1490 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1491 resdesc
= stopccn_result_codes
[rescode
];
1493 else if (message
== 14)
1495 if (rescode
<= MAX_CDN_RESULT_CODE
)
1496 resdesc
= cdn_result_codes
[rescode
];
1499 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Result Code %d: %s\n",
1503 u16 errcode
= ntohs(*(u16
*)(b
+ 2));
1504 const char* errdesc
= "(unknown)";
1505 if (errcode
<= MAX_ERROR_CODE
)
1506 errdesc
= error_codes
[errcode
];
1507 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error Code %d: %s\n",
1511 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error String: %.*s\n",
1517 case 2: // protocol version
1519 version
= ntohs(*(u16
*) (b
));
1520 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Protocol version = %d\n", version
);
1521 if (version
&& version
!= 0x0100)
1522 { // allow 0.0 and 1.0
1523 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Bad protocol version %04X\n",
1530 case 3: // framing capabilities
1531 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Framing capabilities\n");
1533 case 4: // bearer capabilities
1534 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Bearer capabilities\n");
1536 case 5: // tie breaker
1537 // We never open tunnels, so we don't care about tie breakers
1538 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Tie breaker\n");
1540 case 6: // firmware revision
1541 // LOG(4, ntohl(addr->sin_addr.s_addr), s, t, "Firmware revision\n");
1543 case 7: // host name
1544 memset(tunnel
[t
].hostname
, 0, 128);
1545 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1546 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1547 // TBA - to send to RADIUS
1549 case 8: // vendor name
1550 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1551 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1552 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1554 case 9: // assigned tunnel
1555 tunnel
[t
].far
= ntohs(*(u16
*) (b
));
1556 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1558 case 10: // rx window
1559 tunnel
[t
].window
= ntohs(*(u16
*) (b
));
1560 if (!tunnel
[t
].window
)
1561 tunnel
[t
].window
= 1; // window of 0 is silly
1562 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1564 case 11: // Challenge
1566 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " LAC requested CHAP authentication for tunnel\n");
1567 build_chap_response(b
, 2, n
, &chapresponse
);
1570 case 13: // Response
1571 // Why did they send a response? We never challenge.
1572 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " received unexpected challenge response\n");
1575 case 14: // assigned session
1576 asession
= session
[s
].far
= ntohs(*(u16
*) (b
));
1577 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " assigned session = %d\n", asession
);
1579 case 15: // call serial number
1580 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " call serial number = %d\n", ntohl(*(u32
*)b
));
1582 case 18: // bearer type
1583 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " bearer type = %d\n", ntohl(*(u32
*)b
));
1586 case 19: // framing type
1587 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " framing type = %d\n", ntohl(*(u32
*)b
));
1590 case 21: // called number
1591 memset(called
, 0, MAXTEL
);
1592 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1593 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Called <%s>\n", called
);
1595 case 22: // calling number
1596 memset(calling
, 0, MAXTEL
);
1597 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1598 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Calling <%s>\n", calling
);
1602 case 24: // tx connect speed
1605 session
[s
].tx_connect_speed
= ntohl(*(u32
*)b
);
1609 // AS5300s send connect speed as a string
1611 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1612 session
[s
].tx_connect_speed
= atol(tmp
);
1614 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " TX connect speed <%u>\n",
1615 session
[s
].tx_connect_speed
);
1617 case 38: // rx connect speed
1620 session
[s
].rx_connect_speed
= ntohl(*(u32
*)b
);
1624 // AS5300s send connect speed as a string
1626 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1627 session
[s
].rx_connect_speed
= atol(tmp
);
1629 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " RX connect speed <%u>\n",
1630 session
[s
].rx_connect_speed
);
1632 case 25: // Physical Channel ID
1634 u32 tmp
= ntohl(*(u32
*)b
);
1635 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Physical Channel ID <%X>\n", tmp
);
1638 case 29: // Proxy Authentication Type
1640 u16 authtype
= ntohs(*(u16
*)b
);
1641 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Type %d (%s)\n",
1642 authtype
, authtypes
[authtype
]);
1643 requestchap
= (authtype
== 2);
1646 case 30: // Proxy Authentication Name
1648 char authname
[64] = {0};
1649 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1650 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Name (%s)\n",
1654 case 31: // Proxy Authentication Challenge
1656 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1657 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Challenge\n");
1660 case 32: // Proxy Authentication ID
1662 u16 authid
= ntohs(*(u16
*)(b
));
1663 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth ID (%d)\n",
1665 if (session
[s
].radius
)
1666 radius
[session
[s
].radius
].id
= authid
;
1669 case 33: // Proxy Authentication Response
1671 char authresp
[64] = {0};
1672 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1673 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Response\n");
1676 case 27: // last send lcp
1677 { // find magic number
1678 u8
*p
= b
, *e
= p
+ n
;
1679 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1681 if (*p
== 5 && p
[1] == 6) // Magic-Number
1682 amagic
= ntohl(*(u32
*) (p
+ 2));
1683 else if (*p
== 3 && p
[1] == 5 && *(u16
*) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1685 else if (*p
== 7) // Protocol-Field-Compression
1686 aflags
|= SESSIONPFC
;
1687 else if (*p
== 8) // Address-and-Control-Field-Compression
1688 aflags
|= SESSIONACFC
;
1693 case 28: // last recv lcp confreq
1695 case 26: // Initial Received LCP CONFREQ
1697 case 39: // seq required - we control it as an LNS anyway...
1699 case 36: // Random Vector
1700 LOG(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1701 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1702 memcpy(session
[s
].random_vector
, b
, n
);
1703 session
[s
].random_vector_length
= n
;
1706 LOG(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Unknown AVP type %d\n", mtype
);
1713 tunnelshutdown(t
, "Unknown Mandatory AVP");
1717 case 1: // SCCRQ - Start Control Connection Request
1719 controlt
*c
= controlnew(2); // sending SCCRP
1720 control16(c
, 2, version
, 1); // protocol version
1721 control32(c
, 3, 3, 1); // framing
1722 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1723 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1724 control16(c
, 9, t
, 1); // assigned tunnel
1725 controladd(c
, t
, s
); // send the resply
1727 tunnel
[t
].state
= TUNNELOPENING
;
1730 tunnel
[t
].state
= TUNNELOPEN
;
1733 tunnel
[t
].state
= TUNNELOPEN
;
1734 controlnull(t
); // ack
1737 controlnull(t
); // ack
1738 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1739 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1742 controlnull(t
); // simply ACK
1756 STAT(session_overflow
);
1757 tunnelshutdown(t
, "No free sessions");
1765 sessionfree
= session
[s
].next
;
1766 memset(&session
[s
], 0, sizeof(session
[s
]));
1768 if (s
> config
->cluster_highest_sessionid
)
1769 config
->cluster_highest_sessionid
= s
;
1771 // make a RADIUS session
1772 if (!(r
= radiusnew(s
)))
1774 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "No free RADIUS sessions for ICRQ\n");
1775 sessionkill(s
, "no free RADIUS sesions");
1779 c
= controlnew(11); // sending ICRP
1780 session
[s
].id
= sessionid
++;
1781 session
[s
].opened
= time(NULL
);
1782 session
[s
].tunnel
= t
;
1783 session
[s
].far
= asession
;
1784 session
[s
].last_packet
= time_now
;
1785 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1786 control16(c
, 14, s
, 1); // assigned session
1787 controladd(c
, t
, s
); // send the reply
1789 // Generate a random challenge
1791 for (n
= 0; n
< 15; n
++)
1792 radius
[r
].auth
[n
] = rand();
1794 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1795 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1796 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1797 STAT(session_created
);
1804 if (amagic
== 0) amagic
= time_now
;
1805 session
[s
].magic
= amagic
; // set magic number
1806 session
[s
].l2tp_flags
= aflags
; // set flags received
1807 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1808 controlnull(t
); // ack
1809 // In CHAP state, request PAP instead
1814 controlnull(t
); // ack
1815 sessionshutdown(s
, "Closed (Received CDN)");
1818 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Missing message type\n");
1821 STAT(tunnel_rx_errors
);
1822 if (mandatorymessage
& 0x80)
1823 tunnelshutdown(t
, "Unknown message");
1825 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown message type %d\n", message
);
1828 if (chapresponse
) free(chapresponse
);
1829 cluster_send_tunnel(t
);
1833 LOG(4, 0, s
, t
, " Got a ZLB ack\n");
1840 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
1841 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1842 { // HDLC address header, discard
1848 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Short ppp length %d\n", l
);
1849 STAT(tunnel_rx_errors
);
1859 prot
= ntohs(*(u16
*) p
);
1864 if (s
&& !session
[s
].tunnel
) // Is something wrong??
1866 if (!config
->cluster_iam_master
)
1868 // Pass it off to the master to deal with..
1869 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1874 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "UDP packet contains session %d "
1875 "but no session[%d].tunnel exists (LAC said"
1876 " tunnel = %d). Dropping packet.\n", s
, s
, t
);
1877 STAT(tunnel_rx_errors
);
1883 LOG(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1884 // I'm pretty sure this isn't right -- mo.
1885 // return; // closing session, PPP not processed
1889 session
[s
].last_packet
= time_now
;
1890 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1891 processpap(t
, s
, p
, l
);
1893 else if (prot
== PPPCHAP
)
1895 session
[s
].last_packet
= time_now
;
1896 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1897 processchap(t
, s
, p
, l
);
1899 else if (prot
== PPPLCP
)
1901 session
[s
].last_packet
= time_now
;
1902 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1903 processlcp(t
, s
, p
, l
);
1905 else if (prot
== PPPIPCP
)
1907 session
[s
].last_packet
= time_now
;
1908 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1909 processipcp(t
, s
, p
, l
);
1911 else if (prot
== PPPCCP
)
1913 session
[s
].last_packet
= time_now
;
1914 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1915 processccp(t
, s
, p
, l
);
1917 else if (prot
== PPPIP
)
1919 session
[s
].last_packet
= time_now
;
1920 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
1922 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1925 processipin(t
, s
, p
, l
);
1929 STAT(tunnel_rx_errors
);
1930 LOG(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown PPP protocol %04X\n", prot
);
1935 // read and process packet on tun
1936 static void processtun(u8
* buf
, int len
)
1938 LOG_HEX(5, "Receive TUN Data", buf
, len
);
1939 STAT(tun_rx_packets
);
1940 INC_STAT(tun_rx_bytes
, len
);
1942 CSTAT(call_processtun
);
1948 LOG(1, 0, 0, 0, "Short tun packet %d bytes\n", len
);
1949 STAT(tun_rx_errors
);
1953 if (*(u16
*) (buf
+ 2) == htons(PKTIP
)) // IP
1954 processipout(buf
, len
);
1959 // Maximum number of actions to complete.
1960 // This is to avoid sending out too many packets
1962 #define MAX_ACTIONS 500
1964 static int regular_cleanups(void)
1966 static sessionidt s
= 0; // Next session to check for actions on.
1970 static clockt next_acct
= 0;
1973 LOG(3, 0, 0, 0, "Begin regular cleanup\n");
1975 for (r
= 1; r
< MAXRADIUS
; r
++)
1977 if (!radius
[r
].state
)
1979 if (radius
[r
].retry
)
1981 if (radius
[r
].retry
<= TIME
)
1984 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
1986 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
1988 // check for expired tunnels
1989 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
1991 STAT(tunnel_timeout
);
1992 tunnelkill(t
, "Expired");
1995 // check for message resend
1996 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
1998 // resend pending messages as timeout on reply
1999 if (tunnel
[t
].retry
<= TIME
)
2001 controlt
*c
= tunnel
[t
].controls
;
2002 u8 w
= tunnel
[t
].window
;
2003 tunnel
[t
].try++; // another try
2004 if (tunnel
[t
].try > 5)
2005 tunnelkill(t
, "Timeout on control message"); // game over
2009 tunnelsend(c
->buf
, c
->length
, t
);
2015 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2017 controlt
*c
= controlnew(6); // sending HELLO
2018 controladd(c
, t
, 0); // send the message
2019 LOG(3, tunnel
[t
].ip
, 0, t
, "Sending HELLO message\n");
2022 // Check for tunnel changes requested from the CLI
2023 if ((a
= cli_tunnel_actions
[t
].action
))
2025 cli_tunnel_actions
[t
].action
= 0;
2026 if (a
& CLI_TUN_KILL
)
2028 LOG(2, tunnel
[t
].ip
, 0, t
, "Dropping tunnel by CLI\n");
2029 tunnelshutdown(t
, "Requested by administrator");
2036 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2039 if (s
> config
->cluster_highest_sessionid
)
2042 if (!session
[s
].tunnel
) // Session isn't in use
2045 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2047 // IPCP has not completed yet. Resend
2048 LOG(3, session
[s
].ip
, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2049 sendipcp(session
[s
].tunnel
, s
);
2052 // check for expired sessions
2053 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2055 sessionkill(s
, "Expired");
2056 if (++count
>= MAX_ACTIONS
) break;
2060 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2061 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2063 sessionkill(s
, "No response to LCP ECHO requests");
2064 STAT(session_timeout
);
2065 if (++count
>= MAX_ACTIONS
) break;
2069 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2070 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2072 u8 b
[MAXCONTROL
] = {0};
2074 u8
*q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
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 static 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
2210 static void mainloop(void)
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
, alen
);
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 static 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(configt
))))
2496 LOG(0, 0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2499 memset(config
, 0, sizeof(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
));
2535 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
2537 LOG(0, 0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
2540 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
2543 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2545 LOG(0, 0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2548 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2551 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2553 LOG(0, 0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2556 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2558 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2560 LOG(0, 0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2563 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2565 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2566 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2567 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2568 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2570 // Put all the sessions on the free list marked as undefined.
2571 for (i
= 1; i
< MAXSESSION
- 1; i
++)
2573 session
[i
].next
= i
+ 1;
2574 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2576 session
[MAXSESSION
- 1].next
= 0;
2579 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2580 for (i
= 1; i
< MAXTUNNEL
- 1; i
++)
2581 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2585 // Grab my hostname unless it's been specified
2586 gethostname(hostname
, sizeof(hostname
));
2587 stripdomain(hostname
);
2590 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2593 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2595 LOG(0, 0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2601 static int assign_ip_address(sessionidt s
)
2605 time_t best_time
= time_now
;
2606 char *u
= session
[s
].user
;
2610 CSTAT(call_assign_ip_address
);
2612 for (i
= 1; i
< ip_pool_size
; i
++)
2614 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2617 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2624 if (ip_address_pool
[i
].last
< best_time
)
2627 if (!(best_time
= ip_address_pool
[i
].last
))
2628 break; // never used, grab this one
2634 LOG(0, 0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2638 session
[s
].ip
= ip_address_pool
[best
].address
;
2639 session
[s
].ip_pool_index
= best
;
2640 ip_address_pool
[best
].assigned
= 1;
2641 ip_address_pool
[best
].last
= time_now
;
2642 ip_address_pool
[best
].session
= s
;
2643 if (session
[s
].walled_garden
)
2644 /* Don't track addresses of users in walled garden (note: this
2645 means that their address isn't "sticky" even if they get
2647 ip_address_pool
[best
].user
[0] = 0;
2649 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2652 LOG(4, ip_address_pool
[best
].address
, s
, session
[s
].tunnel
,
2653 "assign_ip_address(): %s ip address %d from pool\n", reuse
? "Reusing" : "Allocating", best
);
2658 static void free_ip_address(sessionidt s
)
2660 int i
= session
[s
].ip_pool_index
;
2663 CSTAT(call_free_ip_address
);
2666 return; // what the?
2668 if (i
< 0) // Is this actually part of the ip pool?
2672 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2674 ip_address_pool
[i
].assigned
= 0;
2675 ip_address_pool
[i
].session
= 0;
2676 ip_address_pool
[i
].last
= time_now
;
2680 // Fsck the address pool against the session table.
2681 // Normally only called when we become a master.
2683 // This isn't perfect: We aren't keep tracking of which
2684 // users used to have an IP address.
2686 void rebuild_address_pool(void)
2691 // Zero the IP pool allocation, and build
2692 // a map from IP address to pool index.
2693 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2695 ip_address_pool
[i
].assigned
= 0;
2696 ip_address_pool
[i
].session
= 0;
2697 if (!ip_address_pool
[i
].address
)
2700 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2703 for (i
= 0; i
< MAXSESSION
; ++i
)
2706 if (!session
[i
].ip
|| !session
[i
].tunnel
)
2708 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2710 if (session
[i
].ip_pool_index
< 0)
2712 // Not allocated out of the pool.
2713 if (ipid
< 1) // Not found in the pool either? good.
2716 LOG(0, 0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2717 i
, inet_toa(session
[i
].ip
), ipid
);
2719 // Fall through and process it as part of the pool.
2723 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2725 LOG(0, 0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2727 session
[i
].ip_pool_index
= ipid
;
2731 ip_address_pool
[ipid
].assigned
= 1;
2732 ip_address_pool
[ipid
].session
= i
;
2733 ip_address_pool
[ipid
].last
= time_now
;
2734 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2735 session
[i
].ip_pool_index
= ipid
;
2736 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
2741 // Fix the address pool to match a changed session.
2742 // (usually when the master sends us an update).
2743 static void fix_address_pool(int sid
)
2747 ipid
= session
[sid
].ip_pool_index
;
2749 if (ipid
> ip_pool_size
)
2750 return; // Ignore it. rebuild_address_pool will fix it up.
2752 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
2753 return; // Just ignore it. rebuild_address_pool will take care of it.
2755 ip_address_pool
[ipid
].assigned
= 1;
2756 ip_address_pool
[ipid
].session
= sid
;
2757 ip_address_pool
[ipid
].last
= time_now
;
2758 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2762 // Add a block of addresses to the IP pool to hand out.
2764 static void add_to_ip_pool(u32 addr
, u32 mask
)
2768 mask
= 0xffffffff; // Host route only.
2772 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
2775 for (i
= addr
;(i
& mask
) == addr
; ++i
)
2777 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
2778 continue; // Skip 0 and broadcast addresses.
2780 ip_address_pool
[ip_pool_size
].address
= i
;
2781 ip_address_pool
[ip_pool_size
].assigned
= 0;
2783 if (ip_pool_size
>= MAXIPPOOL
)
2785 LOG(0,0,0,0, "Overflowed IP pool adding %s\n", inet_toa(htonl(addr
)) );
2791 // Initialize the IP address pool
2792 static void initippool()
2797 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2799 if (!(f
= fopen(IPPOOLFILE
, "r")))
2801 LOG(0, 0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2805 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2808 buf
[4095] = 0; // Force it to be zero terminated/
2810 if (*buf
== '#' || *buf
== '\n')
2811 continue; // Skip comments / blank lines
2812 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2813 if ((p
= (char *)strchr(buf
, ':')))
2817 src
= inet_addr(buf
);
2818 if (src
== INADDR_NONE
)
2820 LOG(0, 0, 0, 0, "Invalid address pool IP %s\n", buf
);
2823 // This entry is for a specific IP only
2824 if (src
!= config
->bind_address
)
2829 if ((p
= (char *)strchr(pool
, '/')))
2833 u32 start
= 0, mask
= 0;
2835 LOG(2, 0, 0, 0, "Adding IP address range %s\n", buf
);
2837 if (!*p
|| !(numbits
= atoi(p
)))
2839 LOG(0, 0, 0, 0, "Invalid pool range %s\n", buf
);
2842 start
= ntohl(inet_addr(pool
));
2843 mask
= (u32
)(pow(2, numbits
) - 1) << (32 - numbits
);
2845 // Add a static route for this pool
2846 LOG(5, 0, 0, 0, "Adding route for address pool %s/%u\n", inet_toa(htonl(start
)), 32 + mask
);
2847 routeset(0, start
, mask
, 0, 1);
2849 add_to_ip_pool(start
, mask
);
2853 // It's a single ip address
2854 add_to_ip_pool(inet_addr(pool
), 0);
2858 LOG(1, 0, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
2861 void snoop_send_packet(char *packet
, u16 size
, ipt destination
, u16 port
)
2863 struct sockaddr_in snoop_addr
= {0};
2864 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2867 snoop_addr
.sin_family
= AF_INET
;
2868 snoop_addr
.sin_addr
.s_addr
= destination
;
2869 snoop_addr
.sin_port
= ntohs(port
);
2871 LOG(5, 0, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n",
2872 packet
, size
, inet_toa(snoop_addr
.sin_addr
.s_addr
), htons(snoop_addr
.sin_port
));
2873 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
2874 LOG(0, 0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
2875 STAT(packets_snooped
);
2878 static void dump_acct_info()
2880 char filename
[1024];
2882 time_t t
= time(NULL
);
2887 CSTAT(call_dump_acct_info
);
2889 strftime(timestr
, 64, "%Y%m%d%H%M%S", localtime(&t
));
2890 snprintf(filename
, 1024, "%s/%s", config
->accounting_dir
, timestr
);
2892 for (i
= 0; i
< MAXSESSION
; i
++)
2894 if (!session
[i
].opened
|| !session
[i
].ip
|| !(session
[i
].cin
|| session
[i
].cout
) || !*session
[i
].user
|| session
[i
].walled_garden
)
2898 time_t now
= time(NULL
);
2899 if (!(f
= fopen(filename
, "w")))
2901 LOG(0, 0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
2904 LOG(3, 0, 0, 0, "Dumping accounting information to %s\n", filename
);
2905 fprintf(f
, "# dslwatch.pl dump file V1.01\n"
2909 "# format: username ip qos uptxoctets downrxoctets\n",
2915 LOG(4, 0, 0, 0, "Dumping accounting information for %s\n", session
[i
].user
);
2916 fprintf(f
, "%s %s %d %u %u\n",
2917 session
[i
].user
, // username
2918 inet_toa(htonl(session
[i
].ip
)), // ip
2919 (session
[i
].throttle_in
|| session
[i
].throttle_out
) ? 2 : 1, // qos
2920 (u32
)session
[i
].cin
, // uptxoctets
2921 (u32
)session
[i
].cout
); // downrxoctets
2923 session
[i
].pin
= session
[i
].cin
= 0;
2924 session
[i
].pout
= session
[i
].cout
= 0;
2932 int main(int argc
, char *argv
[])
2936 char *optconfig
= CONFIGFILE
;
2938 time(&basetime
); // start clock
2941 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
2946 if (fork()) exit(0);
2948 freopen("/dev/null", "r", stdin
);
2949 freopen("/dev/null", "w", stdout
);
2950 freopen("/dev/null", "w", stderr
);
2959 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
2962 printf("Args are:\n"
2963 "\t-d\t\tDetach from terminal\n"
2964 "\t-c <file>\tConfig file\n"
2965 "\t-h <hostname>\tForce hostname\n"
2973 // Start the timer routine off
2975 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
2976 signal(SIGALRM
, sigalrm_handler
);
2977 siginterrupt(SIGALRM
, 0);
2980 initdata(optdebug
, optconfig
);
2984 init_tbf(config
->num_tbfs
);
2986 LOG(0, 0, 0, 0, "L2TPNS version " VERSION
"\n");
2987 LOG(0, 0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
2988 LOG(0, 0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
2991 rlim
.rlim_cur
= RLIM_INFINITY
;
2992 rlim
.rlim_max
= RLIM_INFINITY
;
2993 // Remove the maximum core size
2994 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
2995 LOG(0, 0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
2996 // Make core dumps go to /tmp
3000 if (config
->scheduler_fifo
)
3003 struct sched_param params
= {0};
3004 params
.sched_priority
= 1;
3006 if (get_nprocs() < 2)
3008 LOG(0, 0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3009 config
->scheduler_fifo
= 0;
3013 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3015 LOG(1, 0, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3019 LOG(0, 0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3020 config
->scheduler_fifo
= 0;
3025 /* Set up the cluster communications port. */
3026 if (cluster_init() < 0)
3030 signal(SIGPIPE
, SIG_IGN
);
3031 bgp_setup(config
->as_number
);
3032 bgp_add_route(config
->bind_address
, 0xffffffff);
3033 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3035 if (config
->neighbour
[i
].name
[0])
3036 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3037 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3038 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3043 LOG(1, 0, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3051 signal(SIGHUP
, sighup_handler
);
3052 signal(SIGTERM
, sigterm_handler
);
3053 signal(SIGINT
, sigterm_handler
);
3054 signal(SIGQUIT
, sigquit_handler
);
3055 signal(SIGCHLD
, sigchild_handler
);
3057 // Prevent us from getting paged out
3058 if (config
->lock_pages
)
3060 if (!mlockall(MCL_CURRENT
))
3061 LOG(1, 0, 0, 0, "Locking pages into memory\n");
3063 LOG(0, 0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3068 // Drop privileges here
3069 if (config
->target_uid
> 0 && geteuid() == 0)
3070 setuid(config
->target_uid
);
3075 /* try to shut BGP down cleanly; with luck the sockets will be
3076 writable since we're out of the select */
3077 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3078 if (bgp_peers
[i
].state
== Established
)
3079 bgp_stop(&bgp_peers
[i
]);
3082 /* remove plugins (so cleanup code gets run) */
3085 // Remove the PID file if we wrote it
3086 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3087 unlink(config
->pid_file
);
3089 /* kill CLI children */
3090 signal(SIGTERM
, SIG_IGN
);
3095 static void sighup_handler(int sig
)
3097 if (log_stream
&& log_stream
!= stderr
)
3106 static void sigalrm_handler(int sig
)
3108 // Log current traffic stats
3110 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3111 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3112 (udp_rx
/ 1024.0 / 1024.0 * 8),
3113 (eth_tx
/ 1024.0 / 1024.0 * 8),
3114 (eth_rx
/ 1024.0 / 1024.0 * 8),
3115 (udp_tx
/ 1024.0 / 1024.0 * 8),
3116 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3117 udp_rx_pkt
, eth_rx_pkt
);
3119 udp_tx
= udp_rx
= 0;
3120 udp_rx_pkt
= eth_rx_pkt
= 0;
3121 eth_tx
= eth_rx
= 0;
3123 if (config
->dump_speed
)
3124 printf("%s\n", config
->bandwidth
);
3126 // Update the internal time counter
3128 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3133 struct param_timer p
= { time_now
};
3134 run_plugins(PLUGIN_TIMER
, &p
);
3139 static void sigterm_handler(int sig
)
3141 LOG(1, 0, 0, 0, "Shutting down cleanly\n");
3142 if (config
->save_state
)
3148 static void sigquit_handler(int sig
)
3152 LOG(1, 0, 0, 0, "Shutting down without saving sessions\n");
3153 for (i
= 1; i
< MAXSESSION
; i
++)
3155 if (session
[i
].opened
)
3156 sessionkill(i
, "L2TPNS Closing");
3158 for (i
= 1; i
< MAXTUNNEL
; i
++)
3160 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3161 tunnelshutdown(i
, "L2TPNS Closing");
3167 static void sigchild_handler(int sig
)
3169 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3173 static void read_state()
3179 char magic
[sizeof(DUMP_MAGIC
) - 1];
3182 if (!config
->save_state
)
3188 if (stat(STATEFILE
, &sb
) < 0)
3194 if (sb
.st_mtime
< (time(NULL
) - 60))
3196 LOG(0, 0, 0, 0, "State file is too old to read, ignoring\n");
3201 f
= fopen(STATEFILE
, "r");
3206 LOG(0, 0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3210 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3212 LOG(0, 0, 0, 0, "Bad state file magic\n");
3216 LOG(1, 0, 0, 0, "Reading state information\n");
3217 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3219 LOG(0, 0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3223 if (buf
[0] > ip_pool_size
)
3225 LOG(0, 0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3229 LOG(2, 0, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3230 for (i
= 0; i
< buf
[0]; i
++)
3232 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3234 LOG(0, 0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3238 if (itmp
.address
!= ip_address_pool
[i
].address
)
3240 LOG(0, 0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3244 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3247 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3249 LOG(0, 0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3253 LOG(2, 0, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3254 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3256 LOG(0, 0, 0, 0, "Error reading tunnel data from state file\n");
3260 for (i
= 0; i
< MAXTUNNEL
; i
++)
3262 tunnel
[i
].controlc
= 0;
3263 tunnel
[i
].controls
= NULL
;
3264 tunnel
[i
].controle
= NULL
;
3265 if (*tunnel
[i
].hostname
)
3266 LOG(3, 0, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3269 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3271 LOG(0, 0, 0, 0, "Error/mismatch reading session header from state file\n");
3275 LOG(2, 0, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3276 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3278 LOG(0, 0, 0, 0, "Error reading session data from state file\n");
3282 for (i
= 0; i
< MAXSESSION
; i
++)
3284 session
[i
].tbf_in
= 0;
3285 session
[i
].tbf_out
= 0;
3286 if (session
[i
].opened
)
3288 LOG(2, 0, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3290 sessionsetup(session
[i
].tunnel
, i
);
3295 LOG(0, 0, 0, 0, "Loaded saved state information\n");
3298 static void dump_state()
3303 if (!config
->save_state
)
3308 if (!(f
= fopen(STATEFILE
, "w")))
3311 LOG(1, 0, 0, 0, "Dumping state information\n");
3313 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3316 LOG(2, 0, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3317 buf
[0] = ip_pool_size
;
3318 buf
[1] = sizeof(ippoolt
);
3319 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3321 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3324 LOG(2, 0, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3326 buf
[1] = sizeof(tunnelt
);
3327 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3329 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3332 LOG(2, 0, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3333 buf
[0] = MAXSESSION
;
3334 buf
[1] = sizeof(sessiont
);
3335 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3337 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3345 LOG(0, 0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3349 static void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
)
3352 *challenge_response
= NULL
;
3354 if (!*config
->l2tpsecret
)
3356 LOG(0, 0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3360 LOG(4, 0, 0, 0, " Building challenge response for CHAP request\n");
3362 *challenge_response
= (char *)calloc(17, 1);
3365 MD5Update(&ctx
, &id
, 1);
3366 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3367 MD5Update(&ctx
, challenge
, challenge_length
);
3368 MD5Final(*challenge_response
, &ctx
);
3373 static int facility_value(char *name
)
3376 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3378 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3379 return facilitynames
[i
].c_val
;
3384 static void update_config()
3387 static int timeout
= 0;
3388 static int interval
= 0;
3398 if (*config
->log_filename
)
3400 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3402 char *p
= config
->log_filename
+ 7;
3405 openlog("l2tpns", LOG_PID
, facility_value(p
));
3409 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3411 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3413 fseek(log_stream
, 0, SEEK_END
);
3414 setbuf(log_stream
, NULL
);
3418 log_stream
= stderr
;
3419 setbuf(log_stream
, NULL
);
3425 log_stream
= stderr
;
3426 setbuf(log_stream
, NULL
);
3431 config
->numradiusservers
= 0;
3432 for (i
= 0; i
< MAXRADSERVER
; i
++)
3433 if (config
->radiusserver
[i
])
3435 config
->numradiusservers
++;
3436 // Set radius port: if not set, take the port from the
3437 // first radius server. For the first radius server,
3438 // take the #defined default value from l2tpns.h
3440 // test twice, In case someone works with
3441 // a secondary radius server without defining
3442 // a primary one, this will work even then.
3443 if (i
>0 && !config
->radiusport
[i
])
3444 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3445 if (!config
->radiusport
[i
])
3446 config
->radiusport
[i
] = RADPORT
;
3449 if (!config
->numradiusservers
)
3451 LOG(0, 0, 0, 0, "No RADIUS servers defined!\n");
3454 config
->num_radfds
= 2 << RADIUS_SHIFT
;
3457 for (i
= 0; i
< MAXPLUGINS
; i
++)
3459 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3462 if (*config
->plugins
[i
])
3465 add_plugin(config
->plugins
[i
]);
3467 else if (*config
->old_plugins
[i
])
3470 remove_plugin(config
->old_plugins
[i
]);
3473 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3474 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
3475 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3476 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3477 if (!*config
->cluster_interface
)
3478 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3480 if (!config
->cluster_hb_interval
)
3481 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3483 if (!config
->cluster_hb_timeout
)
3484 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3486 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3488 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3489 // late, ensure we're sufficiently larger than that
3490 int t
= 4 * config
->cluster_hb_interval
+ 11;
3492 if (config
->cluster_hb_timeout
< t
)
3494 LOG(0,0,0,0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3495 config
->cluster_hb_timeout
= t
;
3498 // Push timing changes to the slaves immediately if we're the master
3499 if (config
->cluster_iam_master
)
3500 cluster_heartbeat();
3502 interval
= config
->cluster_hb_interval
;
3503 timeout
= config
->cluster_hb_timeout
;
3507 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3510 if ((f
= fopen(config
->pid_file
, "w")))
3512 fprintf(f
, "%d\n", getpid());
3514 config
->wrote_pid
= 1;
3518 LOG(0, 0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3522 config
->reload_config
= 0;
3525 static void read_config_file()
3529 if (!config
->config_file
) return;
3530 if (!(f
= fopen(config
->config_file
, "r")))
3532 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3536 LOG(3, 0, 0, 0, "Reading config file %s\n", config
->config_file
);
3538 LOG(3, 0, 0, 0, "Done reading config file\n");
3543 int sessionsetup(tunnelidt t
, sessionidt s
)
3545 // A session now exists, set it up
3551 CSTAT(call_sessionsetup
);
3553 LOG(3, session
[s
].ip
, s
, t
, "Doing session setup for session\n");
3555 if (!session
[s
].ip
|| session
[s
].ip
== 0xFFFFFFFE)
3557 assign_ip_address(s
);
3560 LOG(0, 0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3561 sessionshutdown(s
, "No IP addresses available");
3564 LOG(3, 0, s
, t
, " No IP allocated. Assigned %s from pool\n",
3565 inet_toa(htonl(session
[s
].ip
)));
3569 // Make sure this is right
3570 session
[s
].tunnel
= t
;
3572 // zap old sessions with same IP and/or username
3573 // Don't kill gardened sessions - doing so leads to a DoS
3574 // from someone who doesn't need to know the password
3577 user
= session
[s
].user
;
3578 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3580 if (i
== s
) continue;
3581 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3582 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3583 sessionkill(i
, "Duplicate session for users");
3590 // Add the route for this session.
3591 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3593 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
3594 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
3597 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
3600 // Static IPs need to be routed if not already
3601 // convered by a Framed-Route. Anything else is part
3602 // of the IP address pool and is already routed, it
3603 // just needs to be added to the IP cache.
3604 if (session
[s
].ip_pool_index
== -1) // static ip
3606 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
3609 cache_ipmap(session
[s
].ip
, s
);
3612 if (!session
[s
].unique_id
)
3614 // did this session just finish radius?
3615 LOG(3, session
[s
].ip
, s
, t
, "Sending initial IPCP to client\n");
3617 session
[s
].unique_id
= ++last_id
;
3620 // Run the plugin's against this new session.
3622 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3623 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3626 // Allocate TBFs if throttled
3627 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3628 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3630 session
[s
].last_packet
= time_now
;
3633 char *sessionip
, *tunnelip
;
3634 sessionip
= strdup(inet_toa(htonl(session
[s
].ip
)));
3635 tunnelip
= strdup(inet_toa(htonl(tunnel
[t
].ip
)));
3636 LOG(2, session
[s
].ip
, s
, t
, "Login by %s at %s from %s (%s)\n",
3637 session
[s
].user
, sessionip
, tunnelip
, tunnel
[t
].hostname
);
3638 if (sessionip
) free(sessionip
);
3639 if (tunnelip
) free(tunnelip
);
3642 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3644 return 1; // RADIUS OK and IP allocated, done...
3648 // This session just got dropped on us by the master or something.
3649 // Make sure our tables up up to date...
3651 int load_session(sessionidt s
, sessiont
*new)
3657 if (new->ip_pool_index
>= MAXIPPOOL
||
3658 new->tunnel
>= MAXTUNNEL
)
3660 LOG(0,0,s
,0, "Strange session update received!\n");
3661 // FIXME! What to do here?
3666 // Ok. All sanity checks passed. Now we're committed to
3667 // loading the new session.
3670 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3672 // See if routes/ip cache need updating
3673 if (new->ip
!= session
[s
].ip
)
3676 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3677 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
3678 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
3686 // remove old routes...
3687 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3689 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
3690 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
3693 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
3699 if (session
[s
].ip_pool_index
== -1) // static IP
3701 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
3703 else // It's part of the IP pool, remove it manually.
3704 uncache_ipmap(session
[s
].ip
);
3709 // add new routes...
3710 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
3712 if ((new->ip
& new->route
[i
].mask
) ==
3713 (new->route
[i
].ip
& new->route
[i
].mask
))
3716 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
3722 // If there's a new one, add it.
3723 if (new->ip_pool_index
== -1)
3725 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
3728 cache_ipmap(new->ip
, s
);
3732 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
3733 // for walking the sessions to forward byte counts to the master.
3734 config
->cluster_highest_sessionid
= s
;
3736 // TEMP: old session struct used a u32 to define the throttle
3737 // speed for both up/down, new uses a u16 for each. Deal with
3738 // sessions from an old master for migration.
3739 if (new->throttle_out
== 0 && new->tbf_out
)
3740 new->throttle_out
= new->throttle_in
;
3742 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
3744 // Do fixups into address pool.
3745 if (new->ip_pool_index
!= -1)
3746 fix_address_pool(s
);
3751 static void initplugins()
3755 loaded_plugins
= ll_init();
3756 // Initialize the plugins to nothing
3757 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
3758 plugins
[i
] = ll_init();
3761 static void *open_plugin(char *plugin_name
, int load
)
3763 char path
[256] = "";
3765 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
3766 LOG(2, 0, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
3767 return dlopen(path
, RTLD_NOW
);
3770 // plugin callback to get a config value
3771 static void *getconfig(char *key
, enum config_typet type
)
3775 for (i
= 0; config_values
[i
].key
; i
++)
3777 if (!strcmp(config_values
[i
].key
, key
))
3779 if (config_values
[i
].type
== type
)
3780 return ((void *) config
) + config_values
[i
].offset
;
3782 LOG(1, 0, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
3783 key
, type
, config_values
[i
].type
);
3789 LOG(1, 0, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
3793 static int add_plugin(char *plugin_name
)
3795 static struct pluginfuncs funcs
= {
3800 sessiontbysessionidt
,
3801 sessionidtbysessiont
,
3807 cluster_send_session
,
3810 void *p
= open_plugin(plugin_name
, 1);
3811 int (*initfunc
)(struct pluginfuncs
*);
3816 LOG(1, 0, 0, 0, " Plugin load failed: %s\n", dlerror());
3820 if (ll_contains(loaded_plugins
, p
))
3823 return 0; // already loaded
3827 int *v
= dlsym(p
, "plugin_api_version");
3828 if (!v
|| *v
!= PLUGIN_API_VERSION
)
3830 LOG(1, 0, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
3836 if ((initfunc
= dlsym(p
, "plugin_init")))
3838 if (!initfunc(&funcs
))
3840 LOG(1, 0, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
3846 ll_push(loaded_plugins
, p
);
3848 for (i
= 0; i
< max_plugin_functions
; i
++)
3851 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3853 LOG(3, 0, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
3854 ll_push(plugins
[i
], x
);
3858 LOG(2, 0, 0, 0, " Loaded plugin %s\n", plugin_name
);
3862 static void run_plugin_done(void *plugin
)
3864 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
3870 static int remove_plugin(char *plugin_name
)
3872 void *p
= open_plugin(plugin_name
, 0);
3878 if (ll_contains(loaded_plugins
, p
))
3881 for (i
= 0; i
< max_plugin_functions
; i
++)
3884 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3885 ll_delete(plugins
[i
], x
);
3888 ll_delete(loaded_plugins
, p
);
3894 LOG(2, 0, 0, 0, "Removed plugin %s\n", plugin_name
);
3898 int run_plugins(int plugin_type
, void *data
)
3900 int (*func
)(void *data
);
3902 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
3903 return PLUGIN_RET_ERROR
;
3905 ll_reset(plugins
[plugin_type
]);
3906 while ((func
= ll_next(plugins
[plugin_type
])))
3910 if (r
!= PLUGIN_RET_OK
)
3911 return r
; // stop here
3914 return PLUGIN_RET_OK
;
3917 static void plugins_done()
3921 ll_reset(loaded_plugins
);
3922 while ((p
= ll_next(loaded_plugins
)))
3926 static void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
, int alen
)
3928 struct nsctl request
;
3929 struct nsctl response
;
3930 int type
= unpack_control(&request
, buf
, len
);
3934 if (log_stream
&& config
->debug
>= 4)
3938 LOG(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Bogus control message (%d)\n", type
);
3942 LOG(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Received ");
3943 dump_control(&request
, log_stream
);
3949 case NSCTL_REQ_LOAD
:
3950 if (request
.argc
!= 1)
3952 response
.type
= NSCTL_RES_ERR
;
3954 response
.argv
[0] = "name of plugin required";
3956 else if ((r
= add_plugin(request
.argv
[0])) < 1)
3958 response
.type
= NSCTL_RES_ERR
;
3960 response
.argv
[0] = !r
3961 ? "plugin already loaded"
3962 : "error loading plugin";
3966 response
.type
= NSCTL_RES_OK
;
3972 case NSCTL_REQ_UNLOAD
:
3973 if (request
.argc
!= 1)
3975 response
.type
= NSCTL_RES_ERR
;
3977 response
.argv
[0] = "name of plugin required";
3979 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
3981 response
.type
= NSCTL_RES_ERR
;
3983 response
.argv
[0] = !r
3984 ? "plugin not loaded"
3985 : "plugin not found";
3989 response
.type
= NSCTL_RES_OK
;
3995 case NSCTL_REQ_HELP
:
3996 response
.type
= NSCTL_RES_OK
;
3999 ll_reset(loaded_plugins
);
4000 while ((p
= ll_next(loaded_plugins
)))
4002 char **help
= dlsym(p
, "plugin_control_help");
4003 while (response
.argc
< 0xff && help
&& *help
)
4004 response
.argv
[response
.argc
++] = *help
++;
4009 case NSCTL_REQ_CONTROL
:
4011 struct param_control param
= {
4012 config
->cluster_iam_master
,
4019 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4021 if (r
== PLUGIN_RET_ERROR
)
4023 response
.type
= NSCTL_RES_ERR
;
4025 response
.argv
[0] = param
.additional
4027 : "error returned by plugin";
4029 else if (r
== PLUGIN_RET_NOTMASTER
)
4031 static char msg
[] = "must be run on master: 000.000.000.000";
4033 response
.type
= NSCTL_RES_ERR
;
4035 if (config
->cluster_master_address
)
4037 strcpy(msg
+ 23, inet_toa(config
->cluster_master_address
));
4038 response
.argv
[0] = msg
;
4042 response
.argv
[0] = "must be run on master: none elected";
4045 else if (!(param
.response
& NSCTL_RESPONSE
))
4047 response
.type
= NSCTL_RES_ERR
;
4049 response
.argv
[0] = param
.response
4050 ? "unrecognised response value from plugin"
4051 : "unhandled action";
4055 response
.type
= param
.response
;
4057 if (param
.additional
)
4060 response
.argv
[0] = param
.additional
;
4068 response
.type
= NSCTL_RES_ERR
;
4070 response
.argv
[0] = "error unpacking control packet";
4073 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4076 LOG(2, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Failed to allocate nsctl response\n");
4080 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4083 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4084 if (log_stream
&& config
->debug
>= 4)
4086 LOG(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Sent ");
4087 dump_control(&response
, log_stream
);
4091 LOG(2, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Failed to pack nsctl response (%d)\n", r
);
4096 static tunnelidt
new_tunnel()
4099 for (i
= 1; i
< MAXTUNNEL
; i
++)
4101 if (tunnel
[i
].state
== TUNNELFREE
)
4103 LOG(4, 0, 0, i
, "Assigning tunnel ID %d\n", i
);
4104 if (i
> config
->cluster_highest_tunnelid
)
4105 config
->cluster_highest_tunnelid
= i
;
4109 LOG(0, 0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4114 // We're becoming the master. Do any required setup..
4116 // This is principally telling all the plugins that we're
4117 // now a master, and telling them about all the sessions
4118 // that are active too..
4120 void become_master(void)
4123 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4125 // running a bunch of iptables commands is slow and can cause
4126 // the master to drop tunnels on takeover--kludge around the
4127 // problem by forking for the moment (note: race)
4128 if (!fork_and_close())
4130 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4132 if (!session
[s
].tunnel
) // Not an in-use session.
4135 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4141 for (i
= 0; i
< config
->num_radfds
; i
++)
4143 FD_SET(radfds
[i
], &readset
);
4144 if (radfds
[i
] > readset_n
)
4145 readset_n
= radfds
[i
];
4149 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4155 if (CLI_HELP_REQUESTED
)
4156 return CLI_HELP_NO_ARGS
;
4159 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4161 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4164 if (!session
[s
].tunnel
)
4167 idle
= time_now
- session
[s
].last_packet
;
4168 idle
/= 5 ; // In multiples of 5 seconds.
4178 for (i
= 0; i
< 63; ++i
)
4180 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4182 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4183 cli_print(cli
, "%d total sessions open.", count
);
4187 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4193 if (CLI_HELP_REQUESTED
)
4194 return CLI_HELP_NO_ARGS
;
4197 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4199 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4202 if (!session
[s
].tunnel
)
4205 d
= time_now
- session
[s
].opened
;
4208 while (d
> 1 && open
< 32)
4218 for (i
= 0; i
< 30; ++i
)
4220 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4223 cli_print(cli
, "%d total sessions open.", count
);
4229 * This unencodes the AVP using the L2TP CHAP secret and the
4230 * previously stored random vector. It replaces the hidden data with
4231 * the cleartext data and returns the length of the cleartext data
4232 * (including the AVP "header" of 6 bytes).
4234 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4236 static int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
)
4241 u8 working_vector
[16];
4242 uint16_t hidden_length
;
4247 // Find the AVP type.
4248 type
[0] = *(avp
+ 4);
4249 type
[1] = *(avp
+ 5);
4251 // Line up with the hidden data
4252 cursor
= output
= avp
+ 6;
4254 // Compute initial pad
4256 MD5Update(&ctx
, type
, 2);
4257 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4258 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4259 MD5Final(digest
, &ctx
);
4261 // Get hidden length
4262 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4264 // Keep these for later use
4265 working_vector
[0] = *cursor
;
4266 working_vector
[1] = *(cursor
+ 1);
4269 if (hidden_length
> length
- 8)
4271 LOG(1, 0, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4275 /* Decrypt remainder */
4277 todo
= hidden_length
;
4280 working_vector
[done
] = *cursor
;
4281 *output
= digest
[done
] ^ *cursor
;
4286 if (done
== 16 && todo
)
4288 // Compute new digest
4291 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4292 MD5Update(&ctx
, &working_vector
, 16);
4293 MD5Final(digest
, &ctx
);
4297 return hidden_length
+ 6;