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.69 2004/12/16 03:03:41 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 // Counters for shutdown sessions
145 static sessiont shut_acct
[8192];
146 static sessionidt shut_acct_n
= 0;
148 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
149 sessiont
*session
= NULL
; // Array of session structures.
150 sessioncountt
*sess_count
= NULL
; // Array of partial per-session traffic counters.
151 radiust
*radius
= NULL
; // Array of radius structures.
152 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
153 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
154 static controlt
*controlfree
= 0;
155 struct Tstats
*_statistics
= NULL
;
157 struct Tringbuffer
*ringbuffer
= NULL
;
160 static void cache_ipmap(ipt ip
, int s
);
161 static void uncache_ipmap(ipt ip
);
162 static void free_ip_address(sessionidt s
);
163 static void dump_acct_info(int all
);
164 static void sighup_handler(int sig
);
165 static void sigalrm_handler(int sig
);
166 static void sigterm_handler(int sig
);
167 static void sigquit_handler(int sig
);
168 static void sigchild_handler(int sig
);
169 static void read_state(void);
170 static void dump_state(void);
171 static void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
);
172 static void update_config(void);
173 static void read_config_file(void);
174 static void initplugins(void);
175 static int add_plugin(char *plugin_name
);
176 static int remove_plugin(char *plugin_name
);
177 static void plugins_done(void);
178 static void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
, int alen
);
179 static tunnelidt
new_tunnel(void);
180 static int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
);
182 // return internal time (10ths since process startup)
183 static clockt
now(void)
187 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
190 // work out a retry time based on try number
191 // This is a straight bounded exponential backoff.
192 // Maximum re-try time is 32 seconds. (2^5).
193 clockt
backoff(u8
try)
195 if (try > 5) try = 5; // max backoff
196 return now() + 10 * (1 << try);
201 // Log a debug message. Typically called via the LOG macro
203 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
205 static char message
[65536] = {0};
206 static char message2
[65536] = {0};
212 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
213 ringbuffer
->tail
= 0;
214 if (ringbuffer
->tail
== ringbuffer
->head
)
215 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
216 ringbuffer
->head
= 0;
218 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
219 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
220 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
221 va_start(ap
, format
);
222 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
227 if (config
->debug
< level
) return;
229 va_start(ap
, format
);
232 vsnprintf(message2
, 65535, format
, ap
);
233 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
234 fprintf(log_stream
, "%s", message
);
238 vsnprintf(message2
, 65535, format
, ap
);
239 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
240 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
245 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
248 const u8
*d
= (const u8
*)data
;
250 if (config
->debug
< level
) return;
252 // No support for _log_hex to syslog
255 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
256 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
258 for (i
= 0; i
< maxsize
; )
260 fprintf(log_stream
, "%4X: ", i
);
261 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
263 fprintf(log_stream
, "%02X ", d
[j
]);
265 fputs(": ", log_stream
);
268 for (; j
< i
+ 16; j
++)
270 fputs(" ", log_stream
);
272 fputs(": ", log_stream
);
275 fputs(" ", log_stream
);
276 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
278 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
279 fputc(d
[j
], log_stream
);
281 fputc('.', log_stream
);
284 fputs(" ", log_stream
);
288 fputs("\n", log_stream
);
292 setbuf(log_stream
, NULL
);
299 // This adds it to the routing table, advertises it
300 // via BGP if enabled, and stuffs it into the
301 // 'sessionbyip' cache.
303 // 'ip' and 'mask' must be in _host_ order.
305 static void routeset(sessionidt s
, ipt ip
, ipt mask
, ipt gw
, u8 add
)
310 if (!mask
) mask
= 0xffffffff;
312 ip
&= mask
; // Force the ip to be the first one in the route.
314 memset(&r
, 0, sizeof(r
));
315 r
.rt_dev
= config
->tundevice
;
316 r
.rt_dst
.sa_family
= AF_INET
;
317 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
318 r
.rt_gateway
.sa_family
= AF_INET
;
319 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
320 r
.rt_genmask
.sa_family
= AF_INET
;
321 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
322 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
324 r
.rt_flags
|= RTF_GATEWAY
;
325 else if (mask
== 0xffffffff)
326 r
.rt_flags
|= RTF_HOST
;
328 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
329 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
330 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
332 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
333 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
337 bgp_add_route(htonl(ip
), htonl(mask
));
339 bgp_del_route(htonl(ip
), htonl(mask
));
342 // Add/Remove the IPs to the 'sessionbyip' cache.
343 // Note that we add the zero address in the case of
344 // a network route. Roll on CIDR.
346 // Note that 's == 0' implies this is the address pool.
347 // We still cache it here, because it will pre-fill
348 // the malloc'ed tree.
352 if (!add
) // Are we deleting a route?
353 s
= 0; // Caching the session as '0' is the same as uncaching.
355 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
361 // Set up TUN interface
362 static void inittun(void)
365 struct sockaddr_in sin
= {0};
366 memset(&ifr
, 0, sizeof(ifr
));
367 ifr
.ifr_flags
= IFF_TUN
;
369 tunfd
= open(TUNDEVICE
, O_RDWR
);
372 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
376 int flags
= fcntl(tunfd
, F_GETFL
, 0);
377 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
379 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
381 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
384 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
385 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
386 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
388 sin
.sin_family
= AF_INET
;
389 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
390 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
392 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
394 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
397 /* Bump up the qlen to deal with bursts from the network */
399 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
401 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
404 ifr
.ifr_flags
= IFF_UP
;
405 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
407 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
413 static void initudp(void)
416 struct sockaddr_in addr
;
419 memset(&addr
, 0, sizeof(addr
));
420 addr
.sin_family
= AF_INET
;
421 addr
.sin_port
= htons(L2TPPORT
);
422 addr
.sin_addr
.s_addr
= config
->bind_address
;
423 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
424 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
426 int flags
= fcntl(udpfd
, F_GETFL
, 0);
427 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
429 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
431 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
434 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
437 memset(&addr
, 0, sizeof(addr
));
438 addr
.sin_family
= AF_INET
;
439 addr
.sin_port
= htons(NSCTL_PORT
);
440 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
441 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
442 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
444 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
450 // Find session by IP, < 1 for not found
452 // Confusingly enough, this 'ip' must be
453 // in _network_ order. This being the common
454 // case when looking it up from IP packet headers.
456 // We actually use this cache for two things.
457 // #1. For used IP addresses, this maps to the
458 // session ID that it's used by.
459 // #2. For un-used IP addresses, this maps to the
460 // index into the pool table that contains that
464 static int lookup_ipmap(ipt ip
)
467 char **d
= (char **) ip_hash
;
470 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
471 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
472 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
474 s
= (ipt
) d
[(size_t) *a
];
478 sessionidt
sessionbyip(ipt ip
)
480 int s
= lookup_ipmap(ip
);
481 CSTAT(call_sessionbyip
);
483 if (s
> 0 && s
< MAXSESSION
&& session
[s
].tunnel
)
489 // Take an IP address in HOST byte order and
490 // add it to the sessionid by IP cache.
492 // (It's actually cached in network order)
494 static void cache_ipmap(ipt ip
, int s
)
496 ipt nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char*)(&ip))[0]
498 char **d
= (char **) ip_hash
;
501 for (i
= 0; i
< 3; i
++)
503 if (!d
[(size_t) a
[i
]])
505 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof (void *))))
509 d
= (char **) d
[(size_t) a
[i
]];
512 d
[(size_t) a
[3]] = (char *)((int)s
);
515 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
518 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
519 // else a map to an ip pool index.
522 static void uncache_ipmap(ipt ip
)
524 cache_ipmap(ip
, 0); // Assign it to the NULL session.
528 // CLI list to dump current ipcache.
530 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
532 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
536 if (CLI_HELP_REQUESTED
)
537 return CLI_HELP_NO_ARGS
;
539 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
541 for (i
= 0; i
< 256; ++i
)
546 for (j
= 0; j
< 256; ++j
)
551 for (k
= 0; k
< 256; ++k
)
556 for (l
= 0; l
< 256; ++l
)
560 cli_print(cli
, "%7d %d.%d.%d.%d", (int) g
[l
], i
, j
, k
, l
);
566 cli_print(cli
, "%d entries in cache", count
);
571 // Find session by username, 0 for not found
572 // walled garden users aren't authenticated, so the username is
573 // reasonably useless. Ignore them to avoid incorrect actions
575 // This is VERY inefficent. Don't call it often. :)
577 sessionidt
sessionbyuser(char *username
)
580 CSTAT(call_sessionbyuser
);
582 for (s
= 1; s
< MAXSESSION
; ++s
)
584 if (session
[s
].walled_garden
)
585 continue; // Skip walled garden users.
587 if (!strncmp(session
[s
].user
, username
, 128))
591 return 0; // Not found.
594 void send_garp(ipt ip
)
600 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
603 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
606 memset(&ifr
, 0, sizeof(ifr
));
607 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
608 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
610 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
614 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
615 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
617 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
622 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
625 // Find session by username, 0 for not found
626 static sessiont
*sessiontbysessionidt(sessionidt s
)
628 if (!s
|| s
> MAXSESSION
) return NULL
;
632 static sessionidt
sessionidtbysessiont(sessiont
*s
)
634 sessionidt val
= s
-session
;
635 if (s
< session
|| val
> MAXSESSION
) return 0;
639 // actually send a control message for a specific tunnel
640 void tunnelsend(u8
* buf
, u16 l
, tunnelidt t
)
642 struct sockaddr_in addr
;
644 CSTAT(call_tunnelsend
);
648 static int backtrace_count
= 0;
649 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
650 STAT(tunnel_tx_errors
);
651 log_backtrace(backtrace_count
, 5)
657 static int backtrace_count
= 0;
658 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
659 log_backtrace(backtrace_count
, 5)
660 STAT(tunnel_tx_errors
);
664 memset(&addr
, 0, sizeof(addr
));
665 addr
.sin_family
= AF_INET
;
666 *(u32
*) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
667 addr
.sin_port
= htons(tunnel
[t
].port
);
669 // sequence expected, if sequence in message
670 if (*buf
& 0x08) *(u16
*) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
672 // If this is a control message, deal with retries
675 tunnel
[t
].last
= time_now
; // control message sent
676 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
677 if (tunnel
[t
].try > 1)
679 STAT(tunnel_retries
);
680 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
684 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
686 LOG(0, ntohs((*(u16
*) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
687 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
688 STAT(tunnel_tx_errors
);
692 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
693 STAT(tunnel_tx_packets
);
694 INC_STAT(tunnel_tx_bytes
, l
);
698 // Tiny helper function to write data to
701 int tun_write(u8
* data
, int size
)
703 return write(tunfd
, data
, size
);
706 // process outgoing (to tunnel) IP
708 static void processipout(u8
* buf
, int len
)
715 char * data
= buf
; // Keep a copy of the originals.
720 CSTAT(call_processipout
);
722 if (len
< MIN_IP_SIZE
)
724 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
725 STAT(tunnel_tx_errors
);
730 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
731 STAT(tunnel_tx_errors
);
735 // Skip the tun header
739 // Got an IP header now
740 if (*(u8
*)(buf
) >> 4 != 4)
742 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
746 ip
= *(u32
*)(buf
+ 16);
747 if (!(s
= sessionbyip(ip
)))
749 // Is this a packet for a session that doesn't exist?
750 static int rate
= 0; // Number of ICMP packets we've sent this second.
751 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
753 if (last
!= time_now
)
759 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
761 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(u32
*)(buf
+ 12), 0));
762 host_unreachable(*(u32
*)(buf
+ 12), *(u16
*)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
766 t
= session
[s
].tunnel
;
769 // run access-list if any
770 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
775 // Are we throttling this session?
776 if (config
->cluster_iam_master
)
777 tbf_queue_packet(sp
->tbf_out
, data
, size
);
779 master_throttle_packet(sp
->tbf_out
, data
, size
);
782 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
784 // We are walled-gardening this
785 master_garden_packet(s
, data
, size
);
789 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
791 // Add on L2TP header
793 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
795 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
798 // Snooping this session, send it to intercept box
799 if (sp
->snoop_ip
&& sp
->snoop_port
)
800 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
802 sp
->cout
+= len
; // byte count
803 sp
->total_cout
+= len
; // byte count
806 sess_count
[s
].cout
+= len
; // To send to master..
810 // Helper routine for the TBF filters.
811 // Used to send queued data in to the user!
813 static void send_ipout(sessionidt s
, u8
*buf
, int len
)
821 if (len
< 0 || len
> MAXETHER
)
823 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
827 // Skip the tun header
831 ip
= *(u32
*)(buf
+ 16);
836 t
= session
[s
].tunnel
;
839 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
841 // Add on L2TP header
843 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
845 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
848 // Snooping this session.
849 if (sp
->snoop_ip
&& sp
->snoop_port
)
850 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
852 sp
->cout
+= len
; // byte count
853 sp
->total_cout
+= len
; // byte count
856 sess_count
[s
].cout
+= len
; // To send to master..
859 // add an AVP (16 bit)
860 static void control16(controlt
* c
, u16 avp
, u16 val
, u8 m
)
862 u16 l
= (m
? 0x8008 : 0x0008);
863 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
864 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
865 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
866 *(u16
*) (c
->buf
+ c
->length
+ 6) = htons(val
);
870 // add an AVP (32 bit)
871 static void control32(controlt
* c
, u16 avp
, u32 val
, u8 m
)
873 u16 l
= (m
? 0x800A : 0x000A);
874 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
875 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
876 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
877 *(u32
*) (c
->buf
+ c
->length
+ 6) = htonl(val
);
881 // add an AVP (32 bit)
882 static void controls(controlt
* c
, u16 avp
, char *val
, u8 m
)
884 u16 l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
885 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
886 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
887 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
888 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
889 c
->length
+= 6 + strlen(val
);
893 static void controlb(controlt
* c
, u16 avp
, char *val
, unsigned int len
, u8 m
)
895 u16 l
= ((m
? 0x8000 : 0) + len
+ 6);
896 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
897 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
898 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
899 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
900 c
->length
+= 6 + len
;
903 // new control connection
904 static controlt
*controlnew(u16 mtype
)
908 c
= malloc(sizeof(controlt
));
912 controlfree
= c
->next
;
916 *(u16
*) (c
->buf
+ 0) = htons(0xC802); // flags/ver
918 control16(c
, 0, mtype
, 1);
922 // send zero block if nothing is waiting
924 static void controlnull(tunnelidt t
)
927 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
930 *(u16
*) (buf
+ 0) = htons(0xC802); // flags/ver
931 *(u16
*) (buf
+ 2) = htons(12); // length
932 *(u16
*) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
933 *(u16
*) (buf
+ 6) = htons(0); // session
934 *(u16
*) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
935 *(u16
*) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
936 tunnelsend(buf
, 12, t
);
939 // add a control message to a tunnel, and send if within window
940 static void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
942 *(u16
*) (c
->buf
+ 2) = htons(c
->length
); // length
943 *(u16
*) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
944 *(u16
*) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
945 *(u16
*) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
946 tunnel
[t
].ns
++; // advance sequence
947 // link in message in to queue
948 if (tunnel
[t
].controlc
)
949 tunnel
[t
].controle
->next
= c
;
951 tunnel
[t
].controls
= c
;
953 tunnel
[t
].controle
= c
;
954 tunnel
[t
].controlc
++;
956 // send now if space in window
957 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
959 tunnel
[t
].try = 0; // first send
960 tunnelsend(c
->buf
, c
->length
, t
);
965 // Throttle or Unthrottle a session
967 // Throttle the data from/to through a session to no more than
968 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
971 // If either value is -1, the current value is retained for that
974 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
976 if (!session
[s
].tunnel
)
977 return; // No-one home.
979 if (!*session
[s
].user
)
980 return; // User not logged in
984 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
985 if (session
[s
].tbf_in
)
986 free_tbf(session
[s
].tbf_in
);
989 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
991 session
[s
].tbf_in
= 0;
993 session
[s
].throttle_in
= rate_in
;
998 int bytes
= rate_out
* 1024 / 8;
999 if (session
[s
].tbf_out
)
1000 free_tbf(session
[s
].tbf_out
);
1003 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1005 session
[s
].tbf_out
= 0;
1007 session
[s
].throttle_out
= rate_out
;
1011 // add/remove filters from session (-1 = no change)
1012 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1014 if (!session
[s
].tunnel
)
1015 return; // No-one home.
1017 if (!*session
[s
].user
)
1018 return; // User not logged in
1021 if (filter_in
> MAXFILTER
) filter_in
= -1;
1022 if (filter_out
> MAXFILTER
) filter_out
= -1;
1023 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1024 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1028 if (session
[s
].filter_in
)
1029 ip_filters
[session
[s
].filter_in
- 1].used
--;
1032 ip_filters
[filter_in
- 1].used
++;
1034 session
[s
].filter_in
= filter_in
;
1037 if (filter_out
>= 0)
1039 if (session
[s
].filter_out
)
1040 ip_filters
[session
[s
].filter_out
- 1].used
--;
1043 ip_filters
[filter_out
- 1].used
++;
1045 session
[s
].filter_out
= filter_out
;
1049 // start tidy shutdown of session
1050 void sessionshutdown(sessionidt s
, char *reason
)
1052 int walled_garden
= session
[s
].walled_garden
;
1055 CSTAT(call_sessionshutdown
);
1057 if (!session
[s
].tunnel
)
1059 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on a session with no tunnel.\n");
1060 return; // not a live session
1063 if (!session
[s
].die
)
1065 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1066 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1067 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1070 if (session
[s
].opened
&& !walled_garden
&& !session
[s
].die
)
1072 // RADIUS Stop message
1073 u16 r
= session
[s
].radius
;
1076 if (!(r
= radiusnew(s
)))
1078 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1079 STAT(radius_overflow
);
1084 for (n
= 0; n
< 15; n
++)
1085 radius
[r
].auth
[n
] = rand();
1089 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1090 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1092 // Save counters to dump to accounting file
1093 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1094 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1098 { // IP allocated, clear and unroute
1101 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1103 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1104 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1107 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1108 session
[s
].route
[r
].ip
= 0;
1111 if (session
[s
].ip_pool_index
== -1) // static ip
1113 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1120 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1121 throttle_session(s
, 0, 0);
1124 controlt
*c
= controlnew(14); // sending CDN
1125 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1126 control16(c
, 14, s
, 1); // assigned session (our end)
1127 controladd(c
, session
[s
].tunnel
, s
); // send the message
1130 if (!session
[s
].die
)
1131 session
[s
].die
= now() + 150; // Clean up in 15 seconds
1133 // update filter refcounts
1134 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1135 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1137 cluster_send_session(s
);
1140 void sendipcp(tunnelidt t
, sessionidt s
)
1143 u16 r
= session
[s
].radius
;
1146 CSTAT(call_sendipcp
);
1151 if (radius
[r
].state
!= RADIUSIPCP
)
1153 radius
[r
].state
= RADIUSIPCP
;
1157 radius
[r
].retry
= backoff(radius
[r
].try++);
1158 if (radius
[r
].try > 10)
1160 radiusclear(r
, s
); // Clear radius session.
1161 sessionshutdown(s
, "No reply on IPCP");
1165 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1169 q
[1] = r
<< RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1170 *(u16
*) (q
+ 2) = htons(10);
1173 *(u32
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1174 config
->bind_address
? config
->bind_address
:
1175 my_address
; // send my IP
1177 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1178 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1181 // kill a session now
1182 static void sessionkill(sessionidt s
, char *reason
)
1185 CSTAT(call_sessionkill
);
1187 session
[s
].die
= now();
1188 sessionshutdown(s
, reason
); // close radius/routes, etc.
1189 if (session
[s
].radius
)
1190 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1192 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1194 memset(&session
[s
], 0, sizeof(session
[s
]));
1195 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1196 session
[s
].next
= sessionfree
;
1198 cli_session_actions
[s
].action
= 0;
1199 cluster_send_session(s
);
1202 static void tunnelclear(tunnelidt t
)
1205 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1206 tunnel
[t
].state
= TUNNELFREE
;
1209 // kill a tunnel now
1210 static void tunnelkill(tunnelidt t
, char *reason
)
1215 CSTAT(call_tunnelkill
);
1217 tunnel
[t
].state
= TUNNELDIE
;
1219 // free control messages
1220 while ((c
= tunnel
[t
].controls
))
1222 controlt
* n
= c
->next
;
1223 tunnel
[t
].controls
= n
;
1224 tunnel
[t
].controlc
--;
1225 c
->next
= controlfree
;
1229 for (s
= 1; s
< MAXSESSION
; s
++)
1230 if (session
[s
].tunnel
== t
)
1231 sessionkill(s
, reason
);
1235 LOG(1, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1236 cli_tunnel_actions
[s
].action
= 0;
1237 cluster_send_tunnel(t
);
1240 // shut down a tunnel cleanly
1241 static void tunnelshutdown(tunnelidt t
, char *reason
)
1245 CSTAT(call_tunnelshutdown
);
1247 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1249 // never set up, can immediately kill
1250 tunnelkill(t
, reason
);
1253 LOG(1, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1256 for (s
= 1; s
< MAXSESSION
; s
++)
1257 if (session
[s
].tunnel
== t
)
1258 sessionshutdown(s
, reason
);
1260 tunnel
[t
].state
= TUNNELDIE
;
1261 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
1262 cluster_send_tunnel(t
);
1263 // TBA - should we wait for sessions to stop?
1265 controlt
*c
= controlnew(4); // sending StopCCN
1266 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message)
1267 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1268 controladd(c
, t
, 0); // send the message
1272 // read and process packet on tunnel (UDP)
1273 void processudp(u8
* buf
, int len
, struct sockaddr_in
*addr
)
1275 char *chapresponse
= NULL
;
1276 u16 l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1280 CSTAT(call_processudp
);
1284 LOG_HEX(5, "UDP Data", buf
, len
);
1285 STAT(tunnel_rx_packets
);
1286 INC_STAT(tunnel_rx_bytes
, len
);
1289 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
1290 STAT(tunnel_rx_errors
);
1293 if ((buf
[1] & 0x0F) != 2)
1295 LOG(1, 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1296 STAT(tunnel_rx_errors
);
1301 l
= ntohs(*(u16
*) p
);
1304 t
= ntohs(*(u16
*) p
);
1306 s
= ntohs(*(u16
*) p
);
1308 if (s
>= MAXSESSION
)
1310 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
1311 STAT(tunnel_rx_errors
);
1316 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
1317 STAT(tunnel_rx_errors
);
1322 ns
= ntohs(*(u16
*) p
);
1324 nr
= ntohs(*(u16
*) p
);
1329 u16 o
= ntohs(*(u16
*) p
);
1334 LOG(1, s
, t
, "Bad length %d>%d\n", (p
- buf
), l
);
1335 STAT(tunnel_rx_errors
);
1341 u16 message
= 0xFFFF; // message type
1343 u8 mandatorymessage
= 0;
1344 u8 chap
= 0; // if CHAP being used
1345 u16 asession
= 0; // assigned session
1346 u32 amagic
= 0; // magic number
1347 u8 aflags
= 0; // flags from last LCF
1348 u16 version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1349 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1350 char called
[MAXTEL
] = ""; // called number
1351 char calling
[MAXTEL
] = ""; // calling number
1353 if (!config
->cluster_iam_master
)
1355 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1359 if ((*buf
& 0xCA) != 0xC8)
1361 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
1362 STAT(tunnel_rx_errors
);
1366 // check for duplicate tunnel open message
1372 // Is this a duplicate of the first packet? (SCCRQ)
1374 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1376 if (tunnel
[i
].state
!= TUNNELOPENING
||
1377 tunnel
[i
].ip
!= ntohl(*(ipt
*) & addr
->sin_addr
) ||
1378 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1381 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
1386 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1387 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1389 // if no tunnel specified, assign one
1392 if (!(t
= new_tunnel()))
1394 LOG(1, 0, 0, "No more tunnels\n");
1395 STAT(tunnel_overflow
);
1399 tunnel
[t
].ip
= ntohl(*(ipt
*) & addr
->sin_addr
);
1400 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1401 tunnel
[t
].window
= 4; // default window
1402 STAT(tunnel_created
);
1403 LOG(1, 0, t
, " New tunnel from %s:%u ID %d\n",
1404 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
1407 // If the 'ns' just received is not the 'nr' we're
1408 // expecting, just send an ack and drop it.
1410 // if 'ns' is less, then we got a retransmitted packet.
1411 // if 'ns' is greater than missed a packet. Either way
1412 // we should ignore it.
1413 if (ns
!= tunnel
[t
].nr
)
1415 // is this the sequence we were expecting?
1416 STAT(tunnel_rx_errors
);
1417 LOG(1, 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n",
1418 t
, ns
, tunnel
[t
].nr
);
1420 if (l
) // Is this not a ZLB?
1425 // This is used to time out old tunnels
1426 tunnel
[t
].lastrec
= time_now
;
1428 // check sequence of this message
1430 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1431 // some to clear maybe?
1432 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1434 controlt
*c
= tunnel
[t
].controls
;
1435 tunnel
[t
].controls
= c
->next
;
1436 tunnel
[t
].controlc
--;
1437 c
->next
= controlfree
;
1440 tunnel
[t
].try = 0; // we have progress
1443 // receiver advance (do here so quoted correctly in any sends below)
1444 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1445 if (skip
< 0) skip
= 0;
1446 if (skip
< tunnel
[t
].controlc
)
1448 // some control packets can now be sent that were previous stuck out of window
1449 int tosend
= tunnel
[t
].window
- skip
;
1450 controlt
*c
= tunnel
[t
].controls
;
1458 tunnel
[t
].try = 0; // first send
1459 tunnelsend(c
->buf
, c
->length
, t
);
1464 if (!tunnel
[t
].controlc
)
1465 tunnel
[t
].retry
= 0; // caught up
1468 { // if not a null message
1470 while (l
&& !(fatal
& 0x80))
1472 u16 n
= (ntohs(*(u16
*) p
) & 0x3FF);
1479 LOG(1, s
, t
, "Invalid length in AVP\n");
1480 STAT(tunnel_rx_errors
);
1487 // handle hidden AVPs
1488 if (!*config
->l2tpsecret
)
1490 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1494 if (!session
[s
].random_vector_length
)
1496 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
1500 LOG(4, s
, t
, "Hidden AVP\n");
1502 n
= unhide_avp(b
, t
, s
, n
);
1511 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1518 LOG(2, s
, t
, "Unknown AVP vendor %d\n", ntohs(*(u16
*) (b
)));
1523 mtype
= ntohs(*(u16
*) (b
));
1527 LOG(4, s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1530 case 0: // message type
1531 message
= ntohs(*(u16
*) b
);
1532 LOG(4, s
, t
, " Message type = %d (%s)\n", *b
, l2tp_message_types
[message
]);
1533 mandatorymessage
= flags
;
1535 case 1: // result code
1537 u16 rescode
= ntohs(*(u16
*)(b
));
1538 const char* resdesc
= "(unknown)";
1541 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1542 resdesc
= stopccn_result_codes
[rescode
];
1544 else if (message
== 14)
1546 if (rescode
<= MAX_CDN_RESULT_CODE
)
1547 resdesc
= cdn_result_codes
[rescode
];
1550 LOG(4, s
, t
, " Result Code %d: %s\n", rescode
, resdesc
);
1553 u16 errcode
= ntohs(*(u16
*)(b
+ 2));
1554 const char* errdesc
= "(unknown)";
1555 if (errcode
<= MAX_ERROR_CODE
)
1556 errdesc
= error_codes
[errcode
];
1557 LOG(4, s
, t
, " Error Code %d: %s\n", errcode
, errdesc
);
1560 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
1565 case 2: // protocol version
1567 version
= ntohs(*(u16
*) (b
));
1568 LOG(4, s
, t
, " Protocol version = %d\n", version
);
1569 if (version
&& version
!= 0x0100)
1570 { // allow 0.0 and 1.0
1571 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
1577 case 3: // framing capabilities
1578 // LOG(4, s, t, "Framing capabilities\n");
1580 case 4: // bearer capabilities
1581 // LOG(4, s, t, "Bearer capabilities\n");
1583 case 5: // tie breaker
1584 // We never open tunnels, so we don't care about tie breakers
1585 // LOG(4, s, t, "Tie breaker\n");
1587 case 6: // firmware revision
1588 // LOG(4, s, t, "Firmware revision\n");
1590 case 7: // host name
1591 memset(tunnel
[t
].hostname
, 0, 128);
1592 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1593 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1594 // TBA - to send to RADIUS
1596 case 8: // vendor name
1597 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1598 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1599 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1601 case 9: // assigned tunnel
1602 tunnel
[t
].far
= ntohs(*(u16
*) (b
));
1603 LOG(4, s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1605 case 10: // rx window
1606 tunnel
[t
].window
= ntohs(*(u16
*) (b
));
1607 if (!tunnel
[t
].window
)
1608 tunnel
[t
].window
= 1; // window of 0 is silly
1609 LOG(4, s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1611 case 11: // Challenge
1613 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
1614 build_chap_response(b
, 2, n
, &chapresponse
);
1617 case 13: // Response
1618 // Why did they send a response? We never challenge.
1619 LOG(2, s
, t
, " received unexpected challenge response\n");
1622 case 14: // assigned session
1623 asession
= session
[s
].far
= ntohs(*(u16
*) (b
));
1624 LOG(4, s
, t
, " assigned session = %d\n", asession
);
1626 case 15: // call serial number
1627 LOG(4, s
, t
, " call serial number = %d\n", ntohl(*(u32
*)b
));
1629 case 18: // bearer type
1630 LOG(4, s
, t
, " bearer type = %d\n", ntohl(*(u32
*)b
));
1633 case 19: // framing type
1634 LOG(4, s
, t
, " framing type = %d\n", ntohl(*(u32
*)b
));
1637 case 21: // called number
1638 memset(called
, 0, MAXTEL
);
1639 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1640 LOG(4, s
, t
, " Called <%s>\n", called
);
1642 case 22: // calling number
1643 memset(calling
, 0, MAXTEL
);
1644 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1645 LOG(4, s
, t
, " Calling <%s>\n", calling
);
1649 case 24: // tx connect speed
1652 session
[s
].tx_connect_speed
= ntohl(*(u32
*)b
);
1656 // AS5300s send connect speed as a string
1658 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1659 session
[s
].tx_connect_speed
= atol(tmp
);
1661 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
1663 case 38: // rx connect speed
1666 session
[s
].rx_connect_speed
= ntohl(*(u32
*)b
);
1670 // AS5300s send connect speed as a string
1672 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1673 session
[s
].rx_connect_speed
= atol(tmp
);
1675 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
1677 case 25: // Physical Channel ID
1679 u32 tmp
= ntohl(*(u32
*)b
);
1680 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
1683 case 29: // Proxy Authentication Type
1685 u16 authtype
= ntohs(*(u16
*)b
);
1686 LOG(4, s
, t
, " Proxy Auth Type %d (%s)\n", authtype
, authtypes
[authtype
]);
1687 requestchap
= (authtype
== 2);
1690 case 30: // Proxy Authentication Name
1692 char authname
[64] = {0};
1693 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1694 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
1698 case 31: // Proxy Authentication Challenge
1700 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1701 LOG(4, s
, t
, " Proxy Auth Challenge\n");
1704 case 32: // Proxy Authentication ID
1706 u16 authid
= ntohs(*(u16
*)(b
));
1707 LOG(4, s
, t
, " Proxy Auth ID (%d)\n", authid
);
1708 if (session
[s
].radius
)
1709 radius
[session
[s
].radius
].id
= authid
;
1712 case 33: // Proxy Authentication Response
1714 char authresp
[64] = {0};
1715 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1716 LOG(4, s
, t
, " Proxy Auth Response\n");
1719 case 27: // last send lcp
1720 { // find magic number
1721 u8
*p
= b
, *e
= p
+ n
;
1722 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1724 if (*p
== 5 && p
[1] == 6) // Magic-Number
1725 amagic
= ntohl(*(u32
*) (p
+ 2));
1726 else if (*p
== 3 && p
[1] == 5 && *(u16
*) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1728 else if (*p
== 7) // Protocol-Field-Compression
1729 aflags
|= SESSIONPFC
;
1730 else if (*p
== 8) // Address-and-Control-Field-Compression
1731 aflags
|= SESSIONACFC
;
1736 case 28: // last recv lcp confreq
1738 case 26: // Initial Received LCP CONFREQ
1740 case 39: // seq required - we control it as an LNS anyway...
1742 case 36: // Random Vector
1743 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1744 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1745 memcpy(session
[s
].random_vector
, b
, n
);
1746 session
[s
].random_vector_length
= n
;
1749 LOG(2, s
, t
, " Unknown AVP type %d\n", mtype
);
1756 tunnelshutdown(t
, "Unknown Mandatory AVP");
1760 case 1: // SCCRQ - Start Control Connection Request
1762 controlt
*c
= controlnew(2); // sending SCCRP
1763 control16(c
, 2, version
, 1); // protocol version
1764 control32(c
, 3, 3, 1); // framing
1765 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1766 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1767 control16(c
, 9, t
, 1); // assigned tunnel
1768 controladd(c
, t
, s
); // send the resply
1770 tunnel
[t
].state
= TUNNELOPENING
;
1773 tunnel
[t
].state
= TUNNELOPEN
;
1776 tunnel
[t
].state
= TUNNELOPEN
;
1777 controlnull(t
); // ack
1780 controlnull(t
); // ack
1781 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1782 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1785 controlnull(t
); // simply ACK
1799 STAT(session_overflow
);
1800 tunnelshutdown(t
, "No free sessions");
1808 sessionfree
= session
[s
].next
;
1809 memset(&session
[s
], 0, sizeof(session
[s
]));
1811 if (s
> config
->cluster_highest_sessionid
)
1812 config
->cluster_highest_sessionid
= s
;
1814 // make a RADIUS session
1815 if (!(r
= radiusnew(s
)))
1817 LOG(1, s
, t
, "No free RADIUS sessions for ICRQ\n");
1818 sessionkill(s
, "no free RADIUS sesions");
1822 c
= controlnew(11); // sending ICRP
1823 session
[s
].id
= sessionid
++;
1824 session
[s
].opened
= time(NULL
);
1825 session
[s
].tunnel
= t
;
1826 session
[s
].far
= asession
;
1827 session
[s
].last_packet
= time_now
;
1828 LOG(3, s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1829 control16(c
, 14, s
, 1); // assigned session
1830 controladd(c
, t
, s
); // send the reply
1832 // Generate a random challenge
1834 for (n
= 0; n
< 15; n
++)
1835 radius
[r
].auth
[n
] = rand();
1837 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1838 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1839 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1840 STAT(session_created
);
1847 if (amagic
== 0) amagic
= time_now
;
1848 session
[s
].magic
= amagic
; // set magic number
1849 session
[s
].l2tp_flags
= aflags
; // set flags received
1850 LOG(3, s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1851 controlnull(t
); // ack
1852 // In CHAP state, request PAP instead
1857 controlnull(t
); // ack
1858 sessionshutdown(s
, "Closed (Received CDN)");
1861 LOG(1, s
, t
, "Missing message type\n");
1864 STAT(tunnel_rx_errors
);
1865 if (mandatorymessage
& 0x80)
1866 tunnelshutdown(t
, "Unknown message");
1868 LOG(1, s
, t
, "Unknown message type %d\n", message
);
1871 if (chapresponse
) free(chapresponse
);
1872 cluster_send_tunnel(t
);
1876 LOG(4, s
, t
, " Got a ZLB ack\n");
1883 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
1884 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1885 { // HDLC address header, discard
1891 LOG(1, s
, t
, "Short ppp length %d\n", l
);
1892 STAT(tunnel_rx_errors
);
1902 prot
= ntohs(*(u16
*) p
);
1907 if (s
&& !session
[s
].tunnel
) // Is something wrong??
1909 if (!config
->cluster_iam_master
)
1911 // Pass it off to the master to deal with..
1912 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1917 LOG(1, s
, t
, "UDP packet contains session %d but no session[%d].tunnel "
1918 "exists (LAC said tunnel = %d). Dropping packet.\n", s
, s
, t
);
1920 STAT(tunnel_rx_errors
);
1926 session
[s
].last_packet
= time_now
;
1927 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1928 processpap(t
, s
, p
, l
);
1930 else if (prot
== PPPCHAP
)
1932 session
[s
].last_packet
= time_now
;
1933 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1934 processchap(t
, s
, p
, l
);
1936 else if (prot
== PPPLCP
)
1938 session
[s
].last_packet
= time_now
;
1939 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1940 processlcp(t
, s
, p
, l
);
1942 else if (prot
== PPPIPCP
)
1944 session
[s
].last_packet
= time_now
;
1945 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1946 processipcp(t
, s
, p
, l
);
1948 else if (prot
== PPPCCP
)
1950 session
[s
].last_packet
= time_now
;
1951 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1952 processccp(t
, s
, p
, l
);
1954 else if (prot
== PPPIP
)
1958 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1959 return; // closing session, PPP not processed
1962 session
[s
].last_packet
= time_now
;
1963 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
1965 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1969 processipin(t
, s
, p
, l
);
1973 STAT(tunnel_rx_errors
);
1974 LOG(1, s
, t
, "Unknown PPP protocol %04X\n", prot
);
1979 // read and process packet on tun
1980 static void processtun(u8
* buf
, int len
)
1982 LOG_HEX(5, "Receive TUN Data", buf
, len
);
1983 STAT(tun_rx_packets
);
1984 INC_STAT(tun_rx_bytes
, len
);
1986 CSTAT(call_processtun
);
1992 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
1993 STAT(tun_rx_errors
);
1997 if (*(u16
*) (buf
+ 2) == htons(PKTIP
)) // IP
1998 processipout(buf
, len
);
2003 // Maximum number of actions to complete.
2004 // This is to avoid sending out too many packets
2006 #define MAX_ACTIONS 500
2008 static int regular_cleanups(void)
2010 static sessionidt s
= 0; // Next session to check for actions on.
2014 static clockt next_acct
= 0;
2015 static clockt next_shut_acct
= 0;
2018 LOG(3, 0, 0, "Begin regular cleanup\n");
2020 for (r
= 1; r
< MAXRADIUS
; r
++)
2022 if (!radius
[r
].state
)
2024 if (radius
[r
].retry
)
2026 if (radius
[r
].retry
<= TIME
)
2029 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
2031 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
2033 // check for expired tunnels
2034 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2036 STAT(tunnel_timeout
);
2037 tunnelkill(t
, "Expired");
2040 // check for message resend
2041 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2043 // resend pending messages as timeout on reply
2044 if (tunnel
[t
].retry
<= TIME
)
2046 controlt
*c
= tunnel
[t
].controls
;
2047 u8 w
= tunnel
[t
].window
;
2048 tunnel
[t
].try++; // another try
2049 if (tunnel
[t
].try > 5)
2050 tunnelkill(t
, "Timeout on control message"); // game over
2054 tunnelsend(c
->buf
, c
->length
, t
);
2060 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2062 controlt
*c
= controlnew(6); // sending HELLO
2063 controladd(c
, t
, 0); // send the message
2064 LOG(3, 0, t
, "Sending HELLO message\n");
2067 // Check for tunnel changes requested from the CLI
2068 if ((a
= cli_tunnel_actions
[t
].action
))
2070 cli_tunnel_actions
[t
].action
= 0;
2071 if (a
& CLI_TUN_KILL
)
2073 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
2074 tunnelshutdown(t
, "Requested by administrator");
2081 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2084 if (s
> config
->cluster_highest_sessionid
)
2087 if (!session
[s
].tunnel
) // Session isn't in use
2090 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2092 // IPCP has not completed yet. Resend
2093 LOG(3, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2094 sendipcp(session
[s
].tunnel
, s
);
2097 // check for expired sessions
2098 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2100 sessionkill(s
, "Expired");
2101 if (++count
>= MAX_ACTIONS
) break;
2105 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2106 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2108 sessionshutdown(s
, "No response to LCP ECHO requests");
2109 STAT(session_timeout
);
2110 if (++count
>= MAX_ACTIONS
) break;
2114 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2115 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2117 u8 b
[MAXCONTROL
] = {0};
2119 u8
*q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2123 *(u8
*)(q
+ 1) = (time_now
% 255); // ID
2124 *(u16
*)(q
+ 2) = htons(8); // Length
2125 *(u32
*)(q
+ 4) = 0; // Magic Number (not supported)
2127 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2128 (int)(time_now
- session
[s
].last_packet
));
2129 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2130 if (++count
>= MAX_ACTIONS
) break;
2133 // Check for actions requested from the CLI
2134 if ((a
= cli_session_actions
[s
].action
))
2138 cli_session_actions
[s
].action
= 0;
2139 if (a
& CLI_SESS_KILL
)
2141 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2142 sessionshutdown(s
, "Requested by administrator");
2143 a
= 0; // dead, no need to check for other actions
2146 if (a
& CLI_SESS_NOSNOOP
)
2148 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2149 session
[s
].snoop_ip
= 0;
2150 session
[s
].snoop_port
= 0;
2153 else if (a
& CLI_SESS_SNOOP
)
2155 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2156 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
2157 cli_session_actions
[s
].snoop_port
);
2159 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2160 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2164 if (a
& CLI_SESS_NOTHROTTLE
)
2166 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2167 throttle_session(s
, 0, 0);
2170 else if (a
& CLI_SESS_THROTTLE
)
2172 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2173 cli_session_actions
[s
].throttle_in
,
2174 cli_session_actions
[s
].throttle_out
);
2176 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2180 if (a
& CLI_SESS_NOFILTER
)
2182 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
2183 filter_session(s
, 0, 0);
2186 else if (a
& CLI_SESS_FILTER
)
2188 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
2189 cli_session_actions
[s
].filter_in
,
2190 cli_session_actions
[s
].filter_out
);
2192 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
2197 cluster_send_session(s
);
2199 if (++count
>= MAX_ACTIONS
) break;
2203 if (*config
->accounting_dir
)
2205 if (next_acct
<= TIME
)
2207 // Dump accounting data
2208 next_acct
= TIME
+ ACCT_TIME
;
2209 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2212 else if (next_shut_acct
<= TIME
)
2214 // Dump accounting data for shutdown sessions
2215 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2221 if (count
>= MAX_ACTIONS
)
2222 return 1; // Didn't finish!
2224 LOG(3, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count
, config
->cleanup_interval
);
2230 // Are we in the middle of a tunnel update, or radius
2233 static int still_busy(void)
2236 static clockt last_talked
= 0;
2237 static clockt start_busy_wait
= 0;
2238 if (start_busy_wait
== 0)
2239 start_busy_wait
= TIME
;
2241 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2243 if (!tunnel
[i
].controlc
)
2246 if (last_talked
!= TIME
)
2248 LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i
);
2254 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2255 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2257 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2261 for (i
= 1; i
< MAXRADIUS
; i
++)
2263 if (radius
[i
].state
== RADIUSNULL
)
2265 if (radius
[i
].state
== RADIUSWAIT
)
2268 if (last_talked
!= TIME
)
2270 LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2279 static fd_set readset
;
2280 static int readset_n
= 0;
2282 // main loop - gets packets on tun or udp and processes them
2283 static void mainloop(void)
2288 clockt next_cluster_ping
= 0; // send initial ping immediately
2289 time_t next_clean
= time_now
+ config
->cleanup_interval
;
2291 LOG(4, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2292 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2295 FD_SET(udpfd
, &readset
);
2296 FD_SET(tunfd
, &readset
);
2297 FD_SET(controlfd
, &readset
);
2298 FD_SET(clifd
, &readset
);
2299 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2301 if (tunfd
> readset_n
) readset_n
= tunfd
;
2302 if (controlfd
> readset_n
) readset_n
= controlfd
;
2303 if (clifd
> readset_n
) readset_n
= clifd
;
2304 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2306 while (!main_quit
|| still_busy())
2312 int bgp_set
[BGP_NUM_PEERS
];
2315 if (config
->reload_config
)
2317 // Update the config state based on config settings
2321 memcpy(&r
, &readset
, sizeof(fd_set
));
2323 to
.tv_usec
= 100000; // 1/10th of a second.
2327 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2329 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2332 FD_SET(bgp_peers
[i
].sock
, &r
);
2333 if (bgp_peers
[i
].sock
> n
)
2334 n
= bgp_peers
[i
].sock
;
2339 FD_SET(bgp_peers
[i
].sock
, &w
);
2340 if (bgp_peers
[i
].sock
> n
)
2341 n
= bgp_peers
[i
].sock
;
2345 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2347 n
= select(n
+ 1, &r
, 0, 0, &to
);
2353 if (errno
== EINTR
||
2354 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2357 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2363 struct sockaddr_in addr
;
2367 if (FD_ISSET(controlfd
, &r
))
2369 alen
= sizeof(addr
);
2370 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
, alen
);
2375 if (config
->cluster_iam_master
)
2377 for (i
= 0; i
< config
->num_radfds
; i
++)
2379 if (FD_ISSET(radfds
[i
], &r
))
2381 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2388 if (FD_ISSET(clifd
, &r
))
2392 alen
= sizeof(addr
);
2393 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
2399 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
2405 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2407 int isr
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0;
2408 int isw
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0;
2409 bgp_process(&bgp_peers
[i
], isr
, isw
);
2415 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
2418 if (FD_ISSET(udpfd
, &r
))
2420 alen
= sizeof(addr
);
2421 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
2423 processudp(buf
, s
, &addr
);
2433 if (FD_ISSET(tunfd
, &r
))
2435 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
2447 if (FD_ISSET(cluster_sockfd
, &r
))
2449 alen
= sizeof(addr
);
2450 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
2452 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
2456 FD_CLR(cluster_sockfd
, &r
);
2463 // Runs on every machine (master and slaves).
2464 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
2466 // Check to see which of the cluster is still alive..
2468 cluster_send_ping(basetime
); // Only does anything if we're a slave
2469 cluster_check_master(); // ditto.
2471 cluster_heartbeat(); // Only does anything if we're a master.
2472 cluster_check_slaves(); // ditto.
2474 master_update_counts(); // If we're a slave, send our byte counters to our master.
2476 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
2477 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
2479 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
2482 // Run token bucket filtering queue..
2483 // Only run it every 1/10th of a second.
2484 // Runs on all machines both master and slave.
2486 static clockt last_run
= 0;
2487 if (last_run
!= TIME
)
2494 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2495 * something to read, else under load this will never actually run....
2498 if (config
->cluster_iam_master
&& next_clean
<= time_now
)
2500 if (regular_cleanups())
2503 next_clean
= time_now
+ 1 ; // Didn't finish. Check quickly.
2507 next_clean
= time_now
+ config
->cleanup_interval
; // Did. Move to next interval.
2512 // Are we the master and shutting down??
2513 if (config
->cluster_iam_master
)
2514 cluster_heartbeat(); // Flush any queued changes..
2516 // Ok. Notify everyone we're shutting down. If we're
2517 // the master, this will force an election.
2518 cluster_send_ping(0);
2521 // Important!!! We MUST not process any packets past this point!
2524 static void stripdomain(char *host
)
2528 if ((p
= strchr(host
, '.')))
2534 FILE *resolv
= fopen("/etc/resolv.conf", "r");
2540 while (fgets(buf
, sizeof(buf
), resolv
))
2542 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
2545 if (!isspace(buf
[6]))
2549 while (isspace(*b
)) b
++;
2554 while (*b
&& !isspace(*b
)) b
++;
2556 if (buf
[0] == 'd') // domain is canonical
2562 // first search line
2565 // hold, may be subsequent domain line
2566 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
2577 int hl
= strlen(host
);
2578 int dl
= strlen(domain
);
2579 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
2580 host
[hl
-dl
- 1] = 0;
2584 *p
= 0; // everything after first dot
2589 // Init data structures
2590 static void initdata(int optdebug
, char *optconfig
)
2594 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
2596 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
2599 if (!(config
= shared_malloc(sizeof(configt
))))
2601 LOG(0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2604 memset(config
, 0, sizeof(configt
));
2605 time(&config
->start_time
);
2606 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
2607 config
->debug
= optdebug
;
2608 config
->num_tbfs
= MAXTBFS
;
2609 config
->rl_rate
= 28; // 28kbps
2611 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
2613 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
2616 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
2618 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
2622 if (!(sess_count
= shared_malloc(sizeof(sessioncountt
) * MAXSESSION
)))
2624 LOG(0, 0, 0, "Error doing malloc for sessions_count: %s\n", strerror(errno
));
2628 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
2630 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
2634 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
2636 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
2640 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
2642 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
2645 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
2648 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2650 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2653 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2656 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2658 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2661 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2663 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2665 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2668 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2670 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2671 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2672 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2673 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2675 // Put all the sessions on the free list marked as undefined.
2676 for (i
= 1; i
< MAXSESSION
- 1; i
++)
2678 session
[i
].next
= i
+ 1;
2679 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2681 session
[MAXSESSION
- 1].next
= 0;
2684 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2685 for (i
= 1; i
< MAXTUNNEL
- 1; i
++)
2686 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2690 // Grab my hostname unless it's been specified
2691 gethostname(hostname
, sizeof(hostname
));
2692 stripdomain(hostname
);
2695 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2698 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2700 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2706 static int assign_ip_address(sessionidt s
)
2710 time_t best_time
= time_now
;
2711 char *u
= session
[s
].user
;
2715 CSTAT(call_assign_ip_address
);
2717 for (i
= 1; i
< ip_pool_size
; i
++)
2719 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2722 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2729 if (ip_address_pool
[i
].last
< best_time
)
2732 if (!(best_time
= ip_address_pool
[i
].last
))
2733 break; // never used, grab this one
2739 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2743 session
[s
].ip
= ip_address_pool
[best
].address
;
2744 session
[s
].ip_pool_index
= best
;
2745 ip_address_pool
[best
].assigned
= 1;
2746 ip_address_pool
[best
].last
= time_now
;
2747 ip_address_pool
[best
].session
= s
;
2748 if (session
[s
].walled_garden
)
2749 /* Don't track addresses of users in walled garden (note: this
2750 means that their address isn't "sticky" even if they get
2752 ip_address_pool
[best
].user
[0] = 0;
2754 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2757 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
2758 reuse
? "Reusing" : "Allocating", best
);
2763 static void free_ip_address(sessionidt s
)
2765 int i
= session
[s
].ip_pool_index
;
2768 CSTAT(call_free_ip_address
);
2771 return; // what the?
2773 if (i
< 0) // Is this actually part of the ip pool?
2777 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2779 ip_address_pool
[i
].assigned
= 0;
2780 ip_address_pool
[i
].session
= 0;
2781 ip_address_pool
[i
].last
= time_now
;
2785 // Fsck the address pool against the session table.
2786 // Normally only called when we become a master.
2788 // This isn't perfect: We aren't keep tracking of which
2789 // users used to have an IP address.
2791 void rebuild_address_pool(void)
2796 // Zero the IP pool allocation, and build
2797 // a map from IP address to pool index.
2798 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2800 ip_address_pool
[i
].assigned
= 0;
2801 ip_address_pool
[i
].session
= 0;
2802 if (!ip_address_pool
[i
].address
)
2805 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2808 for (i
= 0; i
< MAXSESSION
; ++i
)
2811 if (!session
[i
].ip
|| !session
[i
].tunnel
)
2813 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2815 if (session
[i
].ip_pool_index
< 0)
2817 // Not allocated out of the pool.
2818 if (ipid
< 1) // Not found in the pool either? good.
2821 LOG(0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2822 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
2824 // Fall through and process it as part of the pool.
2828 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2830 LOG(0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2832 session
[i
].ip_pool_index
= ipid
;
2836 ip_address_pool
[ipid
].assigned
= 1;
2837 ip_address_pool
[ipid
].session
= i
;
2838 ip_address_pool
[ipid
].last
= time_now
;
2839 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2840 session
[i
].ip_pool_index
= ipid
;
2841 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
2846 // Fix the address pool to match a changed session.
2847 // (usually when the master sends us an update).
2848 static void fix_address_pool(int sid
)
2852 ipid
= session
[sid
].ip_pool_index
;
2854 if (ipid
> ip_pool_size
)
2855 return; // Ignore it. rebuild_address_pool will fix it up.
2857 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
2858 return; // Just ignore it. rebuild_address_pool will take care of it.
2860 ip_address_pool
[ipid
].assigned
= 1;
2861 ip_address_pool
[ipid
].session
= sid
;
2862 ip_address_pool
[ipid
].last
= time_now
;
2863 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2867 // Add a block of addresses to the IP pool to hand out.
2869 static void add_to_ip_pool(u32 addr
, u32 mask
)
2873 mask
= 0xffffffff; // Host route only.
2877 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
2880 for (i
= addr
;(i
& mask
) == addr
; ++i
)
2882 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
2883 continue; // Skip 0 and broadcast addresses.
2885 ip_address_pool
[ip_pool_size
].address
= i
;
2886 ip_address_pool
[ip_pool_size
].assigned
= 0;
2888 if (ip_pool_size
>= MAXIPPOOL
)
2890 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
2896 // Initialize the IP address pool
2897 static void initippool()
2902 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2904 if (!(f
= fopen(IPPOOLFILE
, "r")))
2906 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2910 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2913 buf
[4095] = 0; // Force it to be zero terminated/
2915 if (*buf
== '#' || *buf
== '\n')
2916 continue; // Skip comments / blank lines
2917 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2918 if ((p
= (char *)strchr(buf
, ':')))
2922 src
= inet_addr(buf
);
2923 if (src
== INADDR_NONE
)
2925 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
2928 // This entry is for a specific IP only
2929 if (src
!= config
->bind_address
)
2934 if ((p
= (char *)strchr(pool
, '/')))
2938 u32 start
= 0, mask
= 0;
2940 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
2942 if (!*p
|| !(numbits
= atoi(p
)))
2944 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
2947 start
= ntohl(inet_addr(pool
));
2948 mask
= (u32
)(pow(2, numbits
) - 1) << (32 - numbits
);
2950 // Add a static route for this pool
2951 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
2952 fmtaddr(htonl(start
), 0), 32 + mask
);
2954 routeset(0, start
, mask
, 0, 1);
2956 add_to_ip_pool(start
, mask
);
2960 // It's a single ip address
2961 add_to_ip_pool(inet_addr(pool
), 0);
2965 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
2968 void snoop_send_packet(char *packet
, u16 size
, ipt destination
, u16 port
)
2970 struct sockaddr_in snoop_addr
= {0};
2971 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2974 snoop_addr
.sin_family
= AF_INET
;
2975 snoop_addr
.sin_addr
.s_addr
= destination
;
2976 snoop_addr
.sin_port
= ntohs(port
);
2978 LOG(5, 0, 0, "Snooping %d byte packet to %s:%d\n", size
,
2979 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
2980 htons(snoop_addr
.sin_port
));
2982 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
2983 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
2985 STAT(packets_snooped
);
2988 static int dump_session(FILE **f
, sessiont
*s
)
2990 if (!s
->opened
|| !s
->ip
|| !(s
->cin
|| s
->cout
) || !*s
->user
|| s
->walled_garden
)
2995 char filename
[1024];
2997 time_t now
= time(NULL
);
2999 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
3000 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
3002 if (!(*f
= fopen(filename
, "w")))
3004 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
3008 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
3009 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
3013 "# format: username ip qos uptxoctets downrxoctets\n",
3019 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
3020 fprintf(*f
, "%s %s %d %u %u\n",
3021 s
->user
, // username
3022 fmtaddr(htonl(s
->ip
), 0), // ip
3023 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
3024 (u32
) s
->cin
, // uptxoctets
3025 (u32
) s
->cout
); // downrxoctets
3027 s
->pin
= s
->cin
= 0;
3028 s
->pout
= s
->cout
= 0;
3033 static void dump_acct_info(int all
)
3039 CSTAT(call_dump_acct_info
);
3043 for (i
= 0; i
< shut_acct_n
; i
++)
3044 dump_session(&f
, &shut_acct
[i
]);
3050 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3051 dump_session(&f
, &session
[i
]);
3058 int main(int argc
, char *argv
[])
3062 char *optconfig
= CONFIGFILE
;
3064 time(&basetime
); // start clock
3067 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
3072 if (fork()) exit(0);
3074 freopen("/dev/null", "r", stdin
);
3075 freopen("/dev/null", "w", stdout
);
3076 freopen("/dev/null", "w", stderr
);
3085 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
3088 printf("Args are:\n"
3089 "\t-d\t\tDetach from terminal\n"
3090 "\t-c <file>\tConfig file\n"
3091 "\t-h <hostname>\tForce hostname\n"
3099 // Start the timer routine off
3101 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3102 signal(SIGALRM
, sigalrm_handler
);
3103 siginterrupt(SIGALRM
, 0);
3106 initdata(optdebug
, optconfig
);
3110 init_tbf(config
->num_tbfs
);
3112 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
3113 LOG(0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
3114 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3117 rlim
.rlim_cur
= RLIM_INFINITY
;
3118 rlim
.rlim_max
= RLIM_INFINITY
;
3119 // Remove the maximum core size
3120 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
3121 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
3123 // Make core dumps go to /tmp
3127 if (config
->scheduler_fifo
)
3130 struct sched_param params
= {0};
3131 params
.sched_priority
= 1;
3133 if (get_nprocs() < 2)
3135 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3136 config
->scheduler_fifo
= 0;
3140 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3142 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3146 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3147 config
->scheduler_fifo
= 0;
3152 /* Set up the cluster communications port. */
3153 if (cluster_init() < 0)
3157 signal(SIGPIPE
, SIG_IGN
);
3158 bgp_setup(config
->as_number
);
3159 bgp_add_route(config
->bind_address
, 0xffffffff);
3160 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3162 if (config
->neighbour
[i
].name
[0])
3163 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3164 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3165 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3170 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3178 signal(SIGHUP
, sighup_handler
);
3179 signal(SIGTERM
, sigterm_handler
);
3180 signal(SIGINT
, sigterm_handler
);
3181 signal(SIGQUIT
, sigquit_handler
);
3182 signal(SIGCHLD
, sigchild_handler
);
3184 // Prevent us from getting paged out
3185 if (config
->lock_pages
)
3187 if (!mlockall(MCL_CURRENT
))
3188 LOG(1, 0, 0, "Locking pages into memory\n");
3190 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3195 // Drop privileges here
3196 if (config
->target_uid
> 0 && geteuid() == 0)
3197 setuid(config
->target_uid
);
3202 /* try to shut BGP down cleanly; with luck the sockets will be
3203 writable since we're out of the select */
3204 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3205 if (bgp_peers
[i
].state
== Established
)
3206 bgp_stop(&bgp_peers
[i
]);
3209 /* remove plugins (so cleanup code gets run) */
3212 // Remove the PID file if we wrote it
3213 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3214 unlink(config
->pid_file
);
3216 /* kill CLI children */
3217 signal(SIGTERM
, SIG_IGN
);
3222 static void sighup_handler(int sig
)
3224 if (log_stream
&& log_stream
!= stderr
)
3233 static void sigalrm_handler(int sig
)
3235 // Log current traffic stats
3237 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3238 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3239 (udp_rx
/ 1024.0 / 1024.0 * 8),
3240 (eth_tx
/ 1024.0 / 1024.0 * 8),
3241 (eth_rx
/ 1024.0 / 1024.0 * 8),
3242 (udp_tx
/ 1024.0 / 1024.0 * 8),
3243 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3244 udp_rx_pkt
, eth_rx_pkt
);
3246 udp_tx
= udp_rx
= 0;
3247 udp_rx_pkt
= eth_rx_pkt
= 0;
3248 eth_tx
= eth_rx
= 0;
3250 if (config
->dump_speed
)
3251 printf("%s\n", config
->bandwidth
);
3253 // Update the internal time counter
3255 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3260 struct param_timer p
= { time_now
};
3261 run_plugins(PLUGIN_TIMER
, &p
);
3266 static void sigterm_handler(int sig
)
3268 LOG(1, 0, 0, "Shutting down cleanly\n");
3269 if (config
->save_state
)
3275 static void sigquit_handler(int sig
)
3279 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3281 if (config
->cluster_iam_master
)
3283 for (i
= 1; i
< MAXSESSION
; i
++)
3285 if (session
[i
].opened
)
3286 sessionkill(i
, "L2TPNS Closing");
3288 for (i
= 1; i
< MAXTUNNEL
; i
++)
3290 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3291 tunnelshutdown(i
, "L2TPNS Closing");
3298 static void sigchild_handler(int sig
)
3300 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3304 static void read_state()
3310 char magic
[sizeof(DUMP_MAGIC
) - 1];
3313 if (!config
->save_state
)
3319 if (stat(STATEFILE
, &sb
) < 0)
3325 if (sb
.st_mtime
< (time(NULL
) - 60))
3327 LOG(0, 0, 0, "State file is too old to read, ignoring\n");
3332 f
= fopen(STATEFILE
, "r");
3337 LOG(0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3341 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3343 LOG(0, 0, 0, "Bad state file magic\n");
3347 LOG(1, 0, 0, "Reading state information\n");
3348 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3350 LOG(0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3354 if (buf
[0] > ip_pool_size
)
3356 LOG(0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3360 LOG(2, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3361 for (i
= 0; i
< buf
[0]; i
++)
3363 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3365 LOG(0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3369 if (itmp
.address
!= ip_address_pool
[i
].address
)
3371 LOG(0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3375 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3378 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3380 LOG(0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3384 LOG(2, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3385 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3387 LOG(0, 0, 0, "Error reading tunnel data from state file\n");
3391 for (i
= 0; i
< MAXTUNNEL
; i
++)
3393 tunnel
[i
].controlc
= 0;
3394 tunnel
[i
].controls
= NULL
;
3395 tunnel
[i
].controle
= NULL
;
3396 if (*tunnel
[i
].hostname
)
3397 LOG(3, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3400 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3402 LOG(0, 0, 0, "Error/mismatch reading session header from state file\n");
3406 LOG(2, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3407 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3409 LOG(0, 0, 0, "Error reading session data from state file\n");
3413 for (i
= 0; i
< MAXSESSION
; i
++)
3415 session
[i
].tbf_in
= 0;
3416 session
[i
].tbf_out
= 0;
3417 if (session
[i
].opened
)
3419 LOG(2, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3421 sessionsetup(session
[i
].tunnel
, i
);
3426 LOG(0, 0, 0, "Loaded saved state information\n");
3429 static void dump_state()
3434 if (!config
->save_state
)
3439 if (!(f
= fopen(STATEFILE
, "w")))
3442 LOG(1, 0, 0, "Dumping state information\n");
3444 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3447 LOG(2, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3448 buf
[0] = ip_pool_size
;
3449 buf
[1] = sizeof(ippoolt
);
3450 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3452 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3455 LOG(2, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3457 buf
[1] = sizeof(tunnelt
);
3458 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3460 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3463 LOG(2, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3464 buf
[0] = MAXSESSION
;
3465 buf
[1] = sizeof(sessiont
);
3466 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3468 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3476 LOG(0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3480 static void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
)
3483 *challenge_response
= NULL
;
3485 if (!*config
->l2tpsecret
)
3487 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3491 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
3493 *challenge_response
= (char *)calloc(17, 1);
3496 MD5Update(&ctx
, &id
, 1);
3497 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3498 MD5Update(&ctx
, challenge
, challenge_length
);
3499 MD5Final(*challenge_response
, &ctx
);
3504 static int facility_value(char *name
)
3507 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3509 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3510 return facilitynames
[i
].c_val
;
3515 static void update_config()
3518 static int timeout
= 0;
3519 static int interval
= 0;
3529 if (*config
->log_filename
)
3531 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3533 char *p
= config
->log_filename
+ 7;
3536 openlog("l2tpns", LOG_PID
, facility_value(p
));
3540 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3542 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3544 fseek(log_stream
, 0, SEEK_END
);
3545 setbuf(log_stream
, NULL
);
3549 log_stream
= stderr
;
3550 setbuf(log_stream
, NULL
);
3556 log_stream
= stderr
;
3557 setbuf(log_stream
, NULL
);
3562 config
->numradiusservers
= 0;
3563 for (i
= 0; i
< MAXRADSERVER
; i
++)
3564 if (config
->radiusserver
[i
])
3566 config
->numradiusservers
++;
3567 // Set radius port: if not set, take the port from the
3568 // first radius server. For the first radius server,
3569 // take the #defined default value from l2tpns.h
3571 // test twice, In case someone works with
3572 // a secondary radius server without defining
3573 // a primary one, this will work even then.
3574 if (i
>0 && !config
->radiusport
[i
])
3575 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3576 if (!config
->radiusport
[i
])
3577 config
->radiusport
[i
] = RADPORT
;
3580 if (!config
->numradiusservers
)
3581 LOG(0, 0, 0, "No RADIUS servers defined!\n");
3583 config
->num_radfds
= 2 << RADIUS_SHIFT
;
3586 for (i
= 0; i
< MAXPLUGINS
; i
++)
3588 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3591 if (*config
->plugins
[i
])
3594 add_plugin(config
->plugins
[i
]);
3596 else if (*config
->old_plugins
[i
])
3599 remove_plugin(config
->old_plugins
[i
]);
3602 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3603 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
3604 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3605 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3606 if (!*config
->cluster_interface
)
3607 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3609 if (!config
->cluster_hb_interval
)
3610 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3612 if (!config
->cluster_hb_timeout
)
3613 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3615 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3617 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3618 // late, ensure we're sufficiently larger than that
3619 int t
= 4 * config
->cluster_hb_interval
+ 11;
3621 if (config
->cluster_hb_timeout
< t
)
3623 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3624 config
->cluster_hb_timeout
= t
;
3627 // Push timing changes to the slaves immediately if we're the master
3628 if (config
->cluster_iam_master
)
3629 cluster_heartbeat();
3631 interval
= config
->cluster_hb_interval
;
3632 timeout
= config
->cluster_hb_timeout
;
3636 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3639 if ((f
= fopen(config
->pid_file
, "w")))
3641 fprintf(f
, "%d\n", getpid());
3643 config
->wrote_pid
= 1;
3647 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3651 config
->reload_config
= 0;
3654 static void read_config_file()
3658 if (!config
->config_file
) return;
3659 if (!(f
= fopen(config
->config_file
, "r")))
3661 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3665 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
3667 LOG(3, 0, 0, "Done reading config file\n");
3672 int sessionsetup(tunnelidt t
, sessionidt s
)
3674 // A session now exists, set it up
3680 CSTAT(call_sessionsetup
);
3682 LOG(3, s
, t
, "Doing session setup for session\n");
3684 if (!session
[s
].ip
|| session
[s
].ip
== 0xFFFFFFFE)
3686 assign_ip_address(s
);
3689 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3690 sessionshutdown(s
, "No IP addresses available");
3693 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
3694 fmtaddr(htonl(session
[s
].ip
), 0));
3698 // Make sure this is right
3699 session
[s
].tunnel
= t
;
3701 // zap old sessions with same IP and/or username
3702 // Don't kill gardened sessions - doing so leads to a DoS
3703 // from someone who doesn't need to know the password
3706 user
= session
[s
].user
;
3707 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3709 if (i
== s
) continue;
3710 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3711 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3712 sessionkill(i
, "Duplicate session for users");
3719 // Add the route for this session.
3720 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3722 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
3723 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
3726 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
3729 // Static IPs need to be routed if not already
3730 // convered by a Framed-Route. Anything else is part
3731 // of the IP address pool and is already routed, it
3732 // just needs to be added to the IP cache.
3733 if (session
[s
].ip_pool_index
== -1) // static ip
3735 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
3738 cache_ipmap(session
[s
].ip
, s
);
3741 if (!session
[s
].unique_id
)
3743 // did this session just finish radius?
3744 LOG(3, s
, t
, "Sending initial IPCP to client\n");
3746 session
[s
].unique_id
= ++last_id
;
3749 // Run the plugin's against this new session.
3751 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3752 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3755 // Allocate TBFs if throttled
3756 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3757 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3759 session
[s
].last_packet
= time_now
;
3761 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
3762 fmtaddr(htonl(session
[s
].ip
), 0),
3763 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
3765 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3767 return 1; // RADIUS OK and IP allocated, done...
3771 // This session just got dropped on us by the master or something.
3772 // Make sure our tables up up to date...
3774 int load_session(sessionidt s
, sessiont
*new)
3780 if (new->ip_pool_index
>= MAXIPPOOL
||
3781 new->tunnel
>= MAXTUNNEL
)
3783 LOG(0, s
, 0, "Strange session update received!\n");
3784 // FIXME! What to do here?
3789 // Ok. All sanity checks passed. Now we're committed to
3790 // loading the new session.
3793 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3795 // See if routes/ip cache need updating
3796 if (new->ip
!= session
[s
].ip
)
3799 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3800 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
3801 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
3809 // remove old routes...
3810 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3812 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
3813 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
3816 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
3822 if (session
[s
].ip_pool_index
== -1) // static IP
3824 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
3826 else // It's part of the IP pool, remove it manually.
3827 uncache_ipmap(session
[s
].ip
);
3832 // add new routes...
3833 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
3835 if ((new->ip
& new->route
[i
].mask
) ==
3836 (new->route
[i
].ip
& new->route
[i
].mask
))
3839 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
3845 // If there's a new one, add it.
3846 if (new->ip_pool_index
== -1)
3848 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
3851 cache_ipmap(new->ip
, s
);
3856 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
3858 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %d\n", (int) new->filter_in
);
3862 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
3864 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %d\n", (int) new->filter_out
);
3865 new->filter_out
= 0;
3868 if (new->filter_in
!= session
[s
].filter_in
)
3870 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
3871 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
3874 if (new->filter_out
!= session
[s
].filter_out
)
3876 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
3877 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
3880 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
3881 // for walking the sessions to forward byte counts to the master.
3882 config
->cluster_highest_sessionid
= s
;
3884 // TEMP: old session struct used a u32 to define the throttle
3885 // speed for both up/down, new uses a u16 for each. Deal with
3886 // sessions from an old master for migration.
3887 if (new->throttle_out
== 0 && new->tbf_out
)
3888 new->throttle_out
= new->throttle_in
;
3890 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
3892 // Do fixups into address pool.
3893 if (new->ip_pool_index
!= -1)
3894 fix_address_pool(s
);
3899 static void initplugins()
3903 loaded_plugins
= ll_init();
3904 // Initialize the plugins to nothing
3905 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
3906 plugins
[i
] = ll_init();
3909 static void *open_plugin(char *plugin_name
, int load
)
3911 char path
[256] = "";
3913 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
3914 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
3915 return dlopen(path
, RTLD_NOW
);
3918 // plugin callback to get a config value
3919 static void *getconfig(char *key
, enum config_typet type
)
3923 for (i
= 0; config_values
[i
].key
; i
++)
3925 if (!strcmp(config_values
[i
].key
, key
))
3927 if (config_values
[i
].type
== type
)
3928 return ((void *) config
) + config_values
[i
].offset
;
3930 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
3931 key
, type
, config_values
[i
].type
);
3937 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
3941 static int add_plugin(char *plugin_name
)
3943 static struct pluginfuncs funcs
= {
3948 sessiontbysessionidt
,
3949 sessionidtbysessiont
,
3955 cluster_send_session
,
3958 void *p
= open_plugin(plugin_name
, 1);
3959 int (*initfunc
)(struct pluginfuncs
*);
3964 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
3968 if (ll_contains(loaded_plugins
, p
))
3971 return 0; // already loaded
3975 int *v
= dlsym(p
, "plugin_api_version");
3976 if (!v
|| *v
!= PLUGIN_API_VERSION
)
3978 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
3984 if ((initfunc
= dlsym(p
, "plugin_init")))
3986 if (!initfunc(&funcs
))
3988 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
3994 ll_push(loaded_plugins
, p
);
3996 for (i
= 0; i
< max_plugin_functions
; i
++)
3999 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4001 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
4002 ll_push(plugins
[i
], x
);
4006 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
4010 static void run_plugin_done(void *plugin
)
4012 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
4018 static int remove_plugin(char *plugin_name
)
4020 void *p
= open_plugin(plugin_name
, 0);
4026 if (ll_contains(loaded_plugins
, p
))
4029 for (i
= 0; i
< max_plugin_functions
; i
++)
4032 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4033 ll_delete(plugins
[i
], x
);
4036 ll_delete(loaded_plugins
, p
);
4042 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
4046 int run_plugins(int plugin_type
, void *data
)
4048 int (*func
)(void *data
);
4050 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
4051 return PLUGIN_RET_ERROR
;
4053 ll_reset(plugins
[plugin_type
]);
4054 while ((func
= ll_next(plugins
[plugin_type
])))
4058 if (r
!= PLUGIN_RET_OK
)
4059 return r
; // stop here
4062 return PLUGIN_RET_OK
;
4065 static void plugins_done()
4069 ll_reset(loaded_plugins
);
4070 while ((p
= ll_next(loaded_plugins
)))
4074 static void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
, int alen
)
4076 struct nsctl request
;
4077 struct nsctl response
;
4078 int type
= unpack_control(&request
, buf
, len
);
4082 if (log_stream
&& config
->debug
>= 4)
4086 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4087 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
4091 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4092 dump_control(&request
, log_stream
);
4098 case NSCTL_REQ_LOAD
:
4099 if (request
.argc
!= 1)
4101 response
.type
= NSCTL_RES_ERR
;
4103 response
.argv
[0] = "name of plugin required";
4105 else if ((r
= add_plugin(request
.argv
[0])) < 1)
4107 response
.type
= NSCTL_RES_ERR
;
4109 response
.argv
[0] = !r
4110 ? "plugin already loaded"
4111 : "error loading plugin";
4115 response
.type
= NSCTL_RES_OK
;
4121 case NSCTL_REQ_UNLOAD
:
4122 if (request
.argc
!= 1)
4124 response
.type
= NSCTL_RES_ERR
;
4126 response
.argv
[0] = "name of plugin required";
4128 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
4130 response
.type
= NSCTL_RES_ERR
;
4132 response
.argv
[0] = !r
4133 ? "plugin not loaded"
4134 : "plugin not found";
4138 response
.type
= NSCTL_RES_OK
;
4144 case NSCTL_REQ_HELP
:
4145 response
.type
= NSCTL_RES_OK
;
4148 ll_reset(loaded_plugins
);
4149 while ((p
= ll_next(loaded_plugins
)))
4151 char **help
= dlsym(p
, "plugin_control_help");
4152 while (response
.argc
< 0xff && help
&& *help
)
4153 response
.argv
[response
.argc
++] = *help
++;
4158 case NSCTL_REQ_CONTROL
:
4160 struct param_control param
= {
4161 config
->cluster_iam_master
,
4168 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4170 if (r
== PLUGIN_RET_ERROR
)
4172 response
.type
= NSCTL_RES_ERR
;
4174 response
.argv
[0] = param
.additional
4176 : "error returned by plugin";
4178 else if (r
== PLUGIN_RET_NOTMASTER
)
4180 static char msg
[] = "must be run on master: 000.000.000.000";
4182 response
.type
= NSCTL_RES_ERR
;
4184 if (config
->cluster_master_address
)
4186 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
4187 response
.argv
[0] = msg
;
4191 response
.argv
[0] = "must be run on master: none elected";
4194 else if (!(param
.response
& NSCTL_RESPONSE
))
4196 response
.type
= NSCTL_RES_ERR
;
4198 response
.argv
[0] = param
.response
4199 ? "unrecognised response value from plugin"
4200 : "unhandled action";
4204 response
.type
= param
.response
;
4206 if (param
.additional
)
4209 response
.argv
[0] = param
.additional
;
4217 response
.type
= NSCTL_RES_ERR
;
4219 response
.argv
[0] = "error unpacking control packet";
4222 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4225 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4229 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4232 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4233 if (log_stream
&& config
->debug
>= 4)
4235 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4236 dump_control(&response
, log_stream
);
4240 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4241 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
4246 static tunnelidt
new_tunnel()
4249 for (i
= 1; i
< MAXTUNNEL
; i
++)
4251 if (tunnel
[i
].state
== TUNNELFREE
)
4253 LOG(4, 0, i
, "Assigning tunnel ID %d\n", i
);
4254 if (i
> config
->cluster_highest_tunnelid
)
4255 config
->cluster_highest_tunnelid
= i
;
4259 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4264 // We're becoming the master. Do any required setup..
4266 // This is principally telling all the plugins that we're
4267 // now a master, and telling them about all the sessions
4268 // that are active too..
4270 void become_master(void)
4273 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4275 // running a bunch of iptables commands is slow and can cause
4276 // the master to drop tunnels on takeover--kludge around the
4277 // problem by forking for the moment (note: race)
4278 if (!fork_and_close())
4280 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4282 if (!session
[s
].tunnel
) // Not an in-use session.
4285 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4291 for (i
= 0; i
< config
->num_radfds
; i
++)
4293 FD_SET(radfds
[i
], &readset
);
4294 if (radfds
[i
] > readset_n
)
4295 readset_n
= radfds
[i
];
4299 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4305 if (CLI_HELP_REQUESTED
)
4306 return CLI_HELP_NO_ARGS
;
4309 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4311 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4314 if (!session
[s
].tunnel
)
4317 idle
= time_now
- session
[s
].last_packet
;
4318 idle
/= 5 ; // In multiples of 5 seconds.
4328 for (i
= 0; i
< 63; ++i
)
4330 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4332 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4333 cli_print(cli
, "%d total sessions open.", count
);
4337 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4343 if (CLI_HELP_REQUESTED
)
4344 return CLI_HELP_NO_ARGS
;
4347 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4349 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4352 if (!session
[s
].tunnel
)
4355 d
= time_now
- session
[s
].opened
;
4358 while (d
> 1 && open
< 32)
4368 for (i
= 0; i
< 30; ++i
)
4370 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4373 cli_print(cli
, "%d total sessions open.", count
);
4379 * This unencodes the AVP using the L2TP CHAP secret and the
4380 * previously stored random vector. It replaces the hidden data with
4381 * the cleartext data and returns the length of the cleartext data
4382 * (including the AVP "header" of 6 bytes).
4384 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4386 static int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
)
4391 u8 working_vector
[16];
4392 uint16_t hidden_length
;
4397 // Find the AVP type.
4398 type
[0] = *(avp
+ 4);
4399 type
[1] = *(avp
+ 5);
4401 // Line up with the hidden data
4402 cursor
= output
= avp
+ 6;
4404 // Compute initial pad
4406 MD5Update(&ctx
, type
, 2);
4407 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4408 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4409 MD5Final(digest
, &ctx
);
4411 // Get hidden length
4412 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4414 // Keep these for later use
4415 working_vector
[0] = *cursor
;
4416 working_vector
[1] = *(cursor
+ 1);
4419 if (hidden_length
> length
- 8)
4421 LOG(1, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4425 /* Decrypt remainder */
4427 todo
= hidden_length
;
4430 working_vector
[done
] = *cursor
;
4431 *output
= digest
[done
] ^ *cursor
;
4436 if (done
== 16 && todo
)
4438 // Compute new digest
4441 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4442 MD5Update(&ctx
, &working_vector
, 16);
4443 MD5Final(digest
, &ctx
);
4447 return hidden_length
+ 6;
4450 static int ip_filter_port(ip_filter_portt
*p
, portt port
)
4454 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
4455 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
4456 case FILTER_PORT_OP_GT
: return port
> p
->port
;
4457 case FILTER_PORT_OP_LT
: return port
< p
->port
;
4458 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
4464 static int ip_filter_flag(u8 op
, u8 sflags
, u8 cflags
, u8 flags
)
4468 case FILTER_FLAG_OP_ANY
:
4469 return (flags
& sflags
) || (~flags
& cflags
);
4471 case FILTER_FLAG_OP_ALL
:
4472 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
4474 case FILTER_FLAG_OP_EST
:
4475 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
4481 int ip_filter(u8
*buf
, int len
, u8 filter
)
4490 ip_filter_rulet
*rule
;
4492 if (len
< 20) // up to end of destination address
4495 if ((*buf
>> 4) != 4) // IPv4
4498 frag_offset
= ntohs(*(u16
*) (buf
+ 6)) & 0x1fff;
4500 src_ip
= *(u32
*) (buf
+ 12);
4501 dst_ip
= *(u32
*) (buf
+ 16);
4503 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
4505 int l
= (buf
[0] & 0xf) * 4; // length of IP header
4506 if (len
< l
+ 4) // ports
4509 src_port
= ntohs(*(u16
*) (buf
+ l
));
4510 dst_port
= ntohs(*(u16
*) (buf
+ l
+ 2));
4511 if (proto
== IPPROTO_TCP
)
4513 if (len
< l
+ 14) // flags
4516 flags
= buf
[l
+ 13] & 0x3f;
4520 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
4522 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
4525 if (rule
->src_wild
!= INADDR_BROADCAST
&&
4526 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
4529 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
4530 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
4535 if (!rule
->frag
|| rule
->action
== FILTER_ACTION_DENY
)
4543 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
4545 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
4548 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
4551 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
4552 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
4559 return rule
->action
== FILTER_ACTION_PERMIT
;