3 // Copyright (c) 2003, 2004, 2005 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.73.2.7 2005/05/06 06:35:18 bodea Exp $";
13 #include <linux/if_tun.h>
18 #include <net/route.h>
21 #include <netinet/in.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
31 #include <sys/resource.h>
39 #include <sys/sysinfo.h>
47 #include "constants.h"
57 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 uint32_t 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 uint32_t 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 uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
80 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
83 static uint32_t 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("packet_limit", max_packets
, INT
),
121 CONFIG("cluster_address", cluster_address
, IP
),
122 CONFIG("cluster_interface", cluster_interface
, STRING
),
123 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
124 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
128 static char *plugin_functions
[] = {
135 "plugin_new_session",
136 "plugin_kill_session",
138 "plugin_radius_response",
139 "plugin_become_master",
140 "plugin_new_session_master",
143 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
145 // Counters for shutdown sessions
146 static sessiont shut_acct
[8192];
147 static sessionidt shut_acct_n
= 0;
149 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
150 sessiont
*session
= NULL
; // Array of session structures.
151 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
152 radiust
*radius
= NULL
; // Array of radius structures.
153 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
154 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
155 static controlt
*controlfree
= 0;
156 struct Tstats
*_statistics
= NULL
;
158 struct Tringbuffer
*ringbuffer
= NULL
;
161 static void cache_ipmap(in_addr_t ip
, int s
);
162 static void uncache_ipmap(in_addr_t ip
);
163 static void free_ip_address(sessionidt s
);
164 static void dump_acct_info(int all
);
165 static void sighup_handler(int sig
);
166 static void sigalrm_handler(int sig
);
167 static void sigterm_handler(int sig
);
168 static void sigquit_handler(int sig
);
169 static void sigchild_handler(int sig
);
170 static void read_state(void);
171 static void dump_state(void);
172 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
);
173 static void update_config(void);
174 static void read_config_file(void);
175 static void initplugins(void);
176 static int add_plugin(char *plugin_name
);
177 static int remove_plugin(char *plugin_name
);
178 static void plugins_done(void);
179 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
);
180 static tunnelidt
new_tunnel(void);
181 static int unhide_avp(uint8_t *avp
, tunnelidt t
, sessionidt s
, uint16_t length
);
183 // return internal time (10ths since process startup)
184 static clockt
now(void)
188 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
191 // work out a retry time based on try number
192 // This is a straight bounded exponential backoff.
193 // Maximum re-try time is 32 seconds. (2^5).
194 clockt
backoff(uint8_t try)
196 if (try > 5) try = 5; // max backoff
197 return now() + 10 * (1 << try);
202 // Log a debug message. Typically called via the LOG macro
204 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
206 static char message
[65536] = {0};
207 static char message2
[65536] = {0};
213 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
214 ringbuffer
->tail
= 0;
215 if (ringbuffer
->tail
== ringbuffer
->head
)
216 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
217 ringbuffer
->head
= 0;
219 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
220 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
221 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
222 va_start(ap
, format
);
223 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
228 if (config
->debug
< level
) return;
230 va_start(ap
, format
);
233 vsnprintf(message2
, 65535, format
, ap
);
234 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
235 fprintf(log_stream
, "%s", message
);
239 vsnprintf(message2
, 65535, format
, ap
);
240 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
241 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
246 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
249 const uint8_t *d
= (const uint8_t *) data
;
251 if (config
->debug
< level
) return;
253 // No support for _log_hex to syslog
256 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
257 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
259 for (i
= 0; i
< maxsize
; )
261 fprintf(log_stream
, "%4X: ", i
);
262 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
264 fprintf(log_stream
, "%02X ", d
[j
]);
266 fputs(": ", log_stream
);
269 for (; j
< i
+ 16; j
++)
271 fputs(" ", log_stream
);
273 fputs(": ", log_stream
);
276 fputs(" ", log_stream
);
277 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
279 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
280 fputc(d
[j
], log_stream
);
282 fputc('.', log_stream
);
285 fputs(" ", log_stream
);
289 fputs("\n", log_stream
);
293 setbuf(log_stream
, NULL
);
300 // This adds it to the routing table, advertises it
301 // via BGP if enabled, and stuffs it into the
302 // 'sessionbyip' cache.
304 // 'ip' and 'mask' must be in _host_ order.
306 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
311 if (!mask
) mask
= 0xffffffff;
313 ip
&= mask
; // Force the ip to be the first one in the route.
315 memset(&r
, 0, sizeof(r
));
316 r
.rt_dev
= config
->tundevice
;
317 r
.rt_dst
.sa_family
= AF_INET
;
318 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
319 r
.rt_gateway
.sa_family
= AF_INET
;
320 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
321 r
.rt_genmask
.sa_family
= AF_INET
;
322 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
323 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
325 r
.rt_flags
|= RTF_GATEWAY
;
326 else if (mask
== 0xffffffff)
327 r
.rt_flags
|= RTF_HOST
;
329 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
330 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
331 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
333 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
334 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
338 bgp_add_route(htonl(ip
), htonl(mask
));
340 bgp_del_route(htonl(ip
), htonl(mask
));
343 // Add/Remove the IPs to the 'sessionbyip' cache.
344 // Note that we add the zero address in the case of
345 // a network route. Roll on CIDR.
347 // Note that 's == 0' implies this is the address pool.
348 // We still cache it here, because it will pre-fill
349 // the malloc'ed tree.
353 if (!add
) // Are we deleting a route?
354 s
= 0; // Caching the session as '0' is the same as uncaching.
356 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
362 // Set up TUN interface
363 static void inittun(void)
366 struct sockaddr_in sin
= {0};
367 memset(&ifr
, 0, sizeof(ifr
));
368 ifr
.ifr_flags
= IFF_TUN
;
370 tunfd
= open(TUNDEVICE
, O_RDWR
);
373 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
377 int flags
= fcntl(tunfd
, F_GETFL
, 0);
378 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
380 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
382 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
385 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
386 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
387 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
389 sin
.sin_family
= AF_INET
;
390 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
391 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
393 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
395 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
398 /* Bump up the qlen to deal with bursts from the network */
400 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
402 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
405 ifr
.ifr_flags
= IFF_UP
;
406 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
408 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
414 static void initudp(void)
417 struct sockaddr_in addr
;
420 memset(&addr
, 0, sizeof(addr
));
421 addr
.sin_family
= AF_INET
;
422 addr
.sin_port
= htons(L2TPPORT
);
423 addr
.sin_addr
.s_addr
= config
->bind_address
;
424 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
425 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
427 int flags
= fcntl(udpfd
, F_GETFL
, 0);
428 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
430 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
432 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
435 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
438 memset(&addr
, 0, sizeof(addr
));
439 addr
.sin_family
= AF_INET
;
440 addr
.sin_port
= htons(NSCTL_PORT
);
441 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
442 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
443 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
445 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
451 // Find session by IP, < 1 for not found
453 // Confusingly enough, this 'ip' must be
454 // in _network_ order. This being the common
455 // case when looking it up from IP packet headers.
457 // We actually use this cache for two things.
458 // #1. For used IP addresses, this maps to the
459 // session ID that it's used by.
460 // #2. For un-used IP addresses, this maps to the
461 // index into the pool table that contains that
465 static int lookup_ipmap(in_addr_t ip
)
467 uint8_t *a
= (uint8_t *) &ip
;
468 uint8_t **d
= (uint8_t **) ip_hash
;
470 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
471 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
472 if (!(d
= (uint8_t **) d
[(size_t) *a
++])) return 0;
474 return (int) (intptr_t) d
[(size_t) *a
];
477 sessionidt
sessionbyip(in_addr_t ip
)
479 int s
= lookup_ipmap(ip
);
480 CSTAT(call_sessionbyip
);
482 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
483 return (sessionidt
) s
;
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(in_addr_t ip
, int s
)
496 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
497 uint8_t *a
= (uint8_t *) &nip
;
498 uint8_t **d
= (uint8_t **) 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
= (uint8_t **) d
[(size_t) a
[i
]];
512 d
[(size_t) a
[3]] = (uint8_t *) (intptr_t) 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(in_addr_t 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) (intptr_t) 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
<= config
->cluster_highest_sessionid
; ++s
)
584 if (!session
[s
].opened
)
587 if (session
[s
].walled_garden
)
588 continue; // Skip walled garden users.
590 if (!strncmp(session
[s
].user
, username
, 128))
594 return 0; // Not found.
597 void send_garp(in_addr_t ip
)
603 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
606 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
609 memset(&ifr
, 0, sizeof(ifr
));
610 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
611 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
613 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
617 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
618 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
620 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
625 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
628 static sessiont
*sessiontbysessionidt(sessionidt s
)
630 if (!s
|| s
>= MAXSESSION
) return NULL
;
634 static sessionidt
sessionidtbysessiont(sessiont
*s
)
636 sessionidt val
= s
-session
;
637 if (s
< session
|| val
>= MAXSESSION
) return 0;
641 // actually send a control message for a specific tunnel
642 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
644 struct sockaddr_in addr
;
646 CSTAT(call_tunnelsend
);
650 static int backtrace_count
= 0;
651 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
652 STAT(tunnel_tx_errors
);
653 log_backtrace(backtrace_count
, 5)
659 static int backtrace_count
= 0;
660 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
661 log_backtrace(backtrace_count
, 5)
662 STAT(tunnel_tx_errors
);
666 memset(&addr
, 0, sizeof(addr
));
667 addr
.sin_family
= AF_INET
;
668 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
669 addr
.sin_port
= htons(tunnel
[t
].port
);
671 // sequence expected, if sequence in message
672 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
674 // If this is a control message, deal with retries
677 tunnel
[t
].last
= time_now
; // control message sent
678 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
679 if (tunnel
[t
].try > 1)
681 STAT(tunnel_retries
);
682 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
686 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
688 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
689 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
690 STAT(tunnel_tx_errors
);
694 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
695 STAT(tunnel_tx_packets
);
696 INC_STAT(tunnel_tx_bytes
, l
);
700 // Tiny helper function to write data to
703 int tun_write(uint8_t * data
, int size
)
705 return write(tunfd
, data
, size
);
708 // process outgoing (to tunnel) IP
710 static void processipout(uint8_t * buf
, int len
)
717 char *data
= buf
; // Keep a copy of the originals.
720 uint8_t b
[MAXETHER
+ 20];
722 CSTAT(call_processipout
);
724 if (len
< MIN_IP_SIZE
)
726 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
732 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
737 // Skip the tun header
741 // Got an IP header now
742 if (*(uint8_t *)(buf
) >> 4 != 4)
744 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
748 ip
= *(uint32_t *)(buf
+ 16);
749 if (!(s
= sessionbyip(ip
)))
751 // Is this a packet for a session that doesn't exist?
752 static int rate
= 0; // Number of ICMP packets we've sent this second.
753 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
755 if (last
!= time_now
)
761 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
763 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
764 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
768 t
= session
[s
].tunnel
;
771 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
772 if (config
->max_packets
> 0)
774 if (sess_local
[s
].last_packet_out
== TIME
)
776 int max
= config
->max_packets
;
778 // All packets for throttled sessions are handled by the
779 // master, so further limit by using the throttle rate.
780 // A bit of a kludge, since throttle rate is in kbps,
781 // but should still be generous given our average DSL
782 // packet size is 200 bytes: a limit of 28kbps equates
783 // to around 180 packets per second.
784 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
785 max
= sp
->throttle_out
;
787 if (++sess_local
[s
].packets_out
> max
)
789 sess_local
[s
].packets_dropped
++;
795 if (sess_local
[s
].packets_dropped
)
797 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
798 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
799 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
800 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
804 sess_local
[s
].last_packet_out
= TIME
;
805 sess_local
[s
].packets_out
= 1;
806 sess_local
[s
].packets_dropped
= 0;
810 // run access-list if any
811 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
816 // Are we throttling this session?
817 if (config
->cluster_iam_master
)
818 tbf_queue_packet(sp
->tbf_out
, data
, size
);
820 master_throttle_packet(sp
->tbf_out
, data
, size
);
823 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
825 // We are walled-gardening this
826 master_garden_packet(s
, data
, size
);
830 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
832 // Add on L2TP header
834 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
836 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
839 // Snooping this session, send it to intercept box
840 if (sp
->snoop_ip
&& sp
->snoop_port
)
841 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
843 sp
->cout
+= len
; // byte count
844 sp
->total_cout
+= len
; // byte count
847 sess_local
[s
].cout
+= len
; // To send to master..
851 // Helper routine for the TBF filters.
852 // Used to send queued data in to the user!
854 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
860 uint8_t b
[MAXETHER
+ 20];
862 if (len
< 0 || len
> MAXETHER
)
864 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
868 // Skip the tun header
872 ip
= *(in_addr_t
*)(buf
+ 16);
877 t
= session
[s
].tunnel
;
880 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
882 // Add on L2TP header
884 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
886 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
889 // Snooping this session.
890 if (sp
->snoop_ip
&& sp
->snoop_port
)
891 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
893 sp
->cout
+= len
; // byte count
894 sp
->total_cout
+= len
; // byte count
897 sess_local
[s
].cout
+= len
; // To send to master..
900 // add an AVP (16 bit)
901 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
903 uint16_t l
= (m
? 0x8008 : 0x0008);
904 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
905 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
906 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
907 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
911 // add an AVP (32 bit)
912 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
914 uint16_t l
= (m
? 0x800A : 0x000A);
915 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
916 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
917 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
918 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
922 // add an AVP (32 bit)
923 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
925 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
926 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
927 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
928 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
929 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
930 c
->length
+= 6 + strlen(val
);
934 static void controlb(controlt
* c
, uint16_t avp
, char *val
, unsigned int len
, uint8_t m
)
936 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
937 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
938 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
939 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
940 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
941 c
->length
+= 6 + len
;
944 // new control connection
945 static controlt
*controlnew(uint16_t mtype
)
949 c
= malloc(sizeof(controlt
));
953 controlfree
= c
->next
;
957 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
959 control16(c
, 0, mtype
, 1);
963 // send zero block if nothing is waiting
965 static void controlnull(tunnelidt t
)
968 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
971 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
972 *(uint16_t *) (buf
+ 2) = htons(12); // length
973 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
974 *(uint16_t *) (buf
+ 6) = htons(0); // session
975 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
976 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
977 tunnelsend(buf
, 12, t
);
980 // add a control message to a tunnel, and send if within window
981 static void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
983 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
984 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
985 *(uint16_t *) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
986 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
987 tunnel
[t
].ns
++; // advance sequence
988 // link in message in to queue
989 if (tunnel
[t
].controlc
)
990 tunnel
[t
].controle
->next
= c
;
992 tunnel
[t
].controls
= c
;
994 tunnel
[t
].controle
= c
;
995 tunnel
[t
].controlc
++;
997 // send now if space in window
998 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1000 tunnel
[t
].try = 0; // first send
1001 tunnelsend(c
->buf
, c
->length
, t
);
1006 // Throttle or Unthrottle a session
1008 // Throttle the data from/to through a session to no more than
1009 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1012 // If either value is -1, the current value is retained for that
1015 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1017 if (!session
[s
].opened
)
1018 return; // No-one home.
1020 if (!*session
[s
].user
)
1021 return; // User not logged in
1025 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1026 if (session
[s
].tbf_in
)
1027 free_tbf(session
[s
].tbf_in
);
1030 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1032 session
[s
].tbf_in
= 0;
1034 session
[s
].throttle_in
= rate_in
;
1039 int bytes
= rate_out
* 1024 / 8;
1040 if (session
[s
].tbf_out
)
1041 free_tbf(session
[s
].tbf_out
);
1044 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1046 session
[s
].tbf_out
= 0;
1048 session
[s
].throttle_out
= rate_out
;
1052 // add/remove filters from session (-1 = no change)
1053 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1055 if (!session
[s
].opened
)
1056 return; // No-one home.
1058 if (!*session
[s
].user
)
1059 return; // User not logged in
1062 if (filter_in
> MAXFILTER
) filter_in
= -1;
1063 if (filter_out
> MAXFILTER
) filter_out
= -1;
1064 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1065 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1069 if (session
[s
].filter_in
)
1070 ip_filters
[session
[s
].filter_in
- 1].used
--;
1073 ip_filters
[filter_in
- 1].used
++;
1075 session
[s
].filter_in
= filter_in
;
1078 if (filter_out
>= 0)
1080 if (session
[s
].filter_out
)
1081 ip_filters
[session
[s
].filter_out
- 1].used
--;
1084 ip_filters
[filter_out
- 1].used
++;
1086 session
[s
].filter_out
= filter_out
;
1090 // start tidy shutdown of session
1091 void sessionshutdown(sessionidt s
, char *reason
)
1093 int walled_garden
= session
[s
].walled_garden
;
1096 CSTAT(call_sessionshutdown
);
1098 if (!session
[s
].opened
)
1100 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1101 return; // not a live session
1104 if (!session
[s
].die
)
1106 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1107 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1108 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1111 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1113 // RADIUS Stop message
1114 uint16_t r
= session
[s
].radius
;
1117 if (!(r
= radiusnew(s
)))
1119 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1120 STAT(radius_overflow
);
1125 for (n
= 0; n
< 15; n
++)
1126 radius
[r
].auth
[n
] = rand();
1130 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1131 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1133 // Save counters to dump to accounting file
1134 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1135 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1139 { // IP allocated, clear and unroute
1142 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1144 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1145 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1148 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1149 session
[s
].route
[r
].ip
= 0;
1152 if (session
[s
].ip_pool_index
== -1) // static ip
1154 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1161 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1162 throttle_session(s
, 0, 0);
1165 controlt
*c
= controlnew(14); // sending CDN
1166 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1167 control16(c
, 14, s
, 1); // assigned session (our end)
1168 controladd(c
, session
[s
].tunnel
, s
); // send the message
1171 if (!session
[s
].die
)
1172 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1174 // update filter refcounts
1175 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1176 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1178 cluster_send_session(s
);
1181 void sendipcp(tunnelidt t
, sessionidt s
)
1183 uint8_t buf
[MAXCONTROL
];
1184 uint16_t r
= session
[s
].radius
;
1187 CSTAT(call_sendipcp
);
1192 if (radius
[r
].state
!= RADIUSIPCP
)
1194 radius
[r
].state
= RADIUSIPCP
;
1198 radius
[r
].retry
= backoff(radius
[r
].try++);
1199 if (radius
[r
].try > 10)
1201 radiusclear(r
, s
); // Clear radius session.
1202 sessionshutdown(s
, "No reply on IPCP");
1206 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1210 q
[1] = r
<< RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1211 *(uint16_t *) (q
+ 2) = htons(10);
1214 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1215 config
->bind_address
? config
->bind_address
:
1216 my_address
; // send my IP
1218 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1219 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1222 // kill a session now
1223 void sessionkill(sessionidt s
, char *reason
)
1226 CSTAT(call_sessionkill
);
1228 if (!session
[s
].opened
) // not alive
1231 if (session
[s
].next
)
1233 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%d)\n", session
[s
].next
);
1237 session
[s
].die
= TIME
;
1238 sessionshutdown(s
, reason
); // close radius/routes, etc.
1239 if (session
[s
].radius
)
1240 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1242 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1244 memset(&session
[s
], 0, sizeof(session
[s
]));
1245 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1246 session
[s
].next
= sessionfree
;
1248 cli_session_actions
[s
].action
= 0;
1249 cluster_send_session(s
);
1252 static void tunnelclear(tunnelidt t
)
1255 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1256 tunnel
[t
].state
= TUNNELFREE
;
1259 // kill a tunnel now
1260 static void tunnelkill(tunnelidt t
, char *reason
)
1265 CSTAT(call_tunnelkill
);
1267 tunnel
[t
].state
= TUNNELDIE
;
1269 // free control messages
1270 while ((c
= tunnel
[t
].controls
))
1272 controlt
* n
= c
->next
;
1273 tunnel
[t
].controls
= n
;
1274 tunnel
[t
].controlc
--;
1275 c
->next
= controlfree
;
1279 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1280 if (session
[s
].tunnel
== t
)
1281 sessionkill(s
, reason
);
1285 LOG(1, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1286 cli_tunnel_actions
[s
].action
= 0;
1287 cluster_send_tunnel(t
);
1290 // shut down a tunnel cleanly
1291 static void tunnelshutdown(tunnelidt t
, char *reason
)
1295 CSTAT(call_tunnelshutdown
);
1297 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1299 // never set up, can immediately kill
1300 tunnelkill(t
, reason
);
1303 LOG(1, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1306 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1307 if (session
[s
].tunnel
== t
)
1308 sessionshutdown(s
, reason
);
1310 tunnel
[t
].state
= TUNNELDIE
;
1311 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
1312 cluster_send_tunnel(t
);
1313 // TBA - should we wait for sessions to stop?
1315 controlt
*c
= controlnew(4); // sending StopCCN
1316 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message)
1317 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1318 controladd(c
, t
, 0); // send the message
1322 // read and process packet on tunnel (UDP)
1323 void processudp(uint8_t * buf
, int len
, struct sockaddr_in
*addr
)
1325 char *chapresponse
= NULL
;
1326 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1327 uint8_t *p
= buf
+ 2;
1330 CSTAT(call_processudp
);
1334 LOG_HEX(5, "UDP Data", buf
, len
);
1335 STAT(tunnel_rx_packets
);
1336 INC_STAT(tunnel_rx_bytes
, len
);
1339 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
1340 STAT(tunnel_rx_errors
);
1343 if ((buf
[1] & 0x0F) != 2)
1345 LOG(1, 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1346 STAT(tunnel_rx_errors
);
1351 l
= ntohs(*(uint16_t *) p
);
1354 t
= ntohs(*(uint16_t *) p
);
1356 s
= ntohs(*(uint16_t *) p
);
1358 if (s
>= MAXSESSION
)
1360 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
1361 STAT(tunnel_rx_errors
);
1366 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
1367 STAT(tunnel_rx_errors
);
1372 ns
= ntohs(*(uint16_t *) p
);
1374 nr
= ntohs(*(uint16_t *) p
);
1379 uint16_t o
= ntohs(*(uint16_t *) p
);
1384 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
1385 STAT(tunnel_rx_errors
);
1391 uint16_t message
= 0xFFFF; // message type
1393 uint8_t mandatorymessage
= 0;
1394 uint8_t chap
= 0; // if CHAP being used
1395 uint16_t asession
= 0; // assigned session
1396 uint32_t amagic
= 0; // magic number
1397 uint8_t aflags
= 0; // flags from last LCF
1398 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1399 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1400 char called
[MAXTEL
] = ""; // called number
1401 char calling
[MAXTEL
] = ""; // calling number
1403 if (!config
->cluster_iam_master
)
1405 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1409 if ((*buf
& 0xCA) != 0xC8)
1411 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
1412 STAT(tunnel_rx_errors
);
1416 // check for duplicate tunnel open message
1422 // Is this a duplicate of the first packet? (SCCRQ)
1424 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1426 if (tunnel
[i
].state
!= TUNNELOPENING
||
1427 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
1428 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1431 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
1436 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1437 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1439 // if no tunnel specified, assign one
1442 if (!(t
= new_tunnel()))
1444 LOG(1, 0, 0, "No more tunnels\n");
1445 STAT(tunnel_overflow
);
1449 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
1450 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1451 tunnel
[t
].window
= 4; // default window
1452 STAT(tunnel_created
);
1453 LOG(1, 0, t
, " New tunnel from %s:%u ID %d\n",
1454 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
1457 // If the 'ns' just received is not the 'nr' we're
1458 // expecting, just send an ack and drop it.
1460 // if 'ns' is less, then we got a retransmitted packet.
1461 // if 'ns' is greater than missed a packet. Either way
1462 // we should ignore it.
1463 if (ns
!= tunnel
[t
].nr
)
1465 // is this the sequence we were expecting?
1466 STAT(tunnel_rx_errors
);
1467 LOG(1, 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n",
1468 t
, ns
, tunnel
[t
].nr
);
1470 if (l
) // Is this not a ZLB?
1475 // This is used to time out old tunnels
1476 tunnel
[t
].lastrec
= time_now
;
1478 // check sequence of this message
1480 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1481 // some to clear maybe?
1482 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1484 controlt
*c
= tunnel
[t
].controls
;
1485 tunnel
[t
].controls
= c
->next
;
1486 tunnel
[t
].controlc
--;
1487 c
->next
= controlfree
;
1490 tunnel
[t
].try = 0; // we have progress
1493 // receiver advance (do here so quoted correctly in any sends below)
1494 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1495 if (skip
< 0) skip
= 0;
1496 if (skip
< tunnel
[t
].controlc
)
1498 // some control packets can now be sent that were previous stuck out of window
1499 int tosend
= tunnel
[t
].window
- skip
;
1500 controlt
*c
= tunnel
[t
].controls
;
1508 tunnel
[t
].try = 0; // first send
1509 tunnelsend(c
->buf
, c
->length
, t
);
1514 if (!tunnel
[t
].controlc
)
1515 tunnel
[t
].retry
= 0; // caught up
1518 { // if not a null message
1520 while (l
&& !(fatal
& 0x80))
1522 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
1529 LOG(1, s
, t
, "Invalid length in AVP\n");
1530 STAT(tunnel_rx_errors
);
1537 // handle hidden AVPs
1538 if (!*config
->l2tpsecret
)
1540 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1544 if (!session
[s
].random_vector_length
)
1546 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
1550 LOG(4, s
, t
, "Hidden AVP\n");
1552 n
= unhide_avp(b
, t
, s
, n
);
1561 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1566 if (*(uint16_t *) (b
))
1568 LOG(2, s
, t
, "Unknown AVP vendor %d\n", ntohs(*(uint16_t *) (b
)));
1573 mtype
= ntohs(*(uint16_t *) (b
));
1577 LOG(4, s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1580 case 0: // message type
1581 message
= ntohs(*(uint16_t *) b
);
1582 LOG(4, s
, t
, " Message type = %d (%s)\n", *b
, l2tp_message_types
[message
]);
1583 mandatorymessage
= flags
;
1585 case 1: // result code
1587 uint16_t rescode
= ntohs(*(uint16_t *) b
);
1588 const char* resdesc
= "(unknown)";
1591 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1592 resdesc
= stopccn_result_codes
[rescode
];
1594 else if (message
== 14)
1596 if (rescode
<= MAX_CDN_RESULT_CODE
)
1597 resdesc
= cdn_result_codes
[rescode
];
1600 LOG(4, s
, t
, " Result Code %d: %s\n", rescode
, resdesc
);
1603 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
1604 const char* errdesc
= "(unknown)";
1605 if (errcode
<= MAX_ERROR_CODE
)
1606 errdesc
= error_codes
[errcode
];
1607 LOG(4, s
, t
, " Error Code %d: %s\n", errcode
, errdesc
);
1610 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
1615 case 2: // protocol version
1617 version
= ntohs(*(uint16_t *) (b
));
1618 LOG(4, s
, t
, " Protocol version = %d\n", version
);
1619 if (version
&& version
!= 0x0100)
1620 { // allow 0.0 and 1.0
1621 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
1627 case 3: // framing capabilities
1628 // LOG(4, s, t, "Framing capabilities\n");
1630 case 4: // bearer capabilities
1631 // LOG(4, s, t, "Bearer capabilities\n");
1633 case 5: // tie breaker
1634 // We never open tunnels, so we don't care about tie breakers
1635 // LOG(4, s, t, "Tie breaker\n");
1637 case 6: // firmware revision
1638 // LOG(4, s, t, "Firmware revision\n");
1640 case 7: // host name
1641 memset(tunnel
[t
].hostname
, 0, 128);
1642 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1643 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1644 // TBA - to send to RADIUS
1646 case 8: // vendor name
1647 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1648 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1649 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1651 case 9: // assigned tunnel
1652 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
1653 LOG(4, s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1655 case 10: // rx window
1656 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
1657 if (!tunnel
[t
].window
)
1658 tunnel
[t
].window
= 1; // window of 0 is silly
1659 LOG(4, s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1661 case 11: // Challenge
1663 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
1664 build_chap_response(b
, 2, n
, &chapresponse
);
1667 case 13: // Response
1668 // Why did they send a response? We never challenge.
1669 LOG(2, s
, t
, " received unexpected challenge response\n");
1672 case 14: // assigned session
1673 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
1674 LOG(4, s
, t
, " assigned session = %d\n", asession
);
1676 case 15: // call serial number
1677 LOG(4, s
, t
, " call serial number = %d\n", ntohl(*(uint32_t *)b
));
1679 case 18: // bearer type
1680 LOG(4, s
, t
, " bearer type = %d\n", ntohl(*(uint32_t *)b
));
1683 case 19: // framing type
1684 LOG(4, s
, t
, " framing type = %d\n", ntohl(*(uint32_t *)b
));
1687 case 21: // called number
1688 memset(called
, 0, MAXTEL
);
1689 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1690 LOG(4, s
, t
, " Called <%s>\n", called
);
1692 case 22: // calling number
1693 memset(calling
, 0, MAXTEL
);
1694 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1695 LOG(4, s
, t
, " Calling <%s>\n", calling
);
1699 case 24: // tx connect speed
1702 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
1706 // AS5300s send connect speed as a string
1708 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1709 session
[s
].tx_connect_speed
= atol(tmp
);
1711 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
1713 case 38: // rx connect speed
1716 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
1720 // AS5300s send connect speed as a string
1722 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1723 session
[s
].rx_connect_speed
= atol(tmp
);
1725 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
1727 case 25: // Physical Channel ID
1729 uint32_t tmp
= ntohl(*(uint32_t *) b
);
1730 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
1733 case 29: // Proxy Authentication Type
1735 uint16_t authtype
= ntohs(*(uint16_t *)b
);
1736 LOG(4, s
, t
, " Proxy Auth Type %d (%s)\n", authtype
, authtypes
[authtype
]);
1737 requestchap
= (authtype
== 2);
1740 case 30: // Proxy Authentication Name
1742 char authname
[64] = {0};
1743 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1744 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
1748 case 31: // Proxy Authentication Challenge
1750 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1751 LOG(4, s
, t
, " Proxy Auth Challenge\n");
1754 case 32: // Proxy Authentication ID
1756 uint16_t authid
= ntohs(*(uint16_t *)(b
));
1757 LOG(4, s
, t
, " Proxy Auth ID (%d)\n", authid
);
1758 if (session
[s
].radius
)
1759 radius
[session
[s
].radius
].id
= authid
;
1762 case 33: // Proxy Authentication Response
1764 char authresp
[64] = {0};
1765 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1766 LOG(4, s
, t
, " Proxy Auth Response\n");
1769 case 27: // last send lcp
1770 { // find magic number
1771 uint8_t *p
= b
, *e
= p
+ n
;
1772 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1774 if (*p
== 5 && p
[1] == 6) // Magic-Number
1775 amagic
= ntohl(*(uint32_t *) (p
+ 2));
1776 else if (*p
== 3 && p
[1] == 5 && *(uint16_t *) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1778 else if (*p
== 7) // Protocol-Field-Compression
1779 aflags
|= SESSIONPFC
;
1780 else if (*p
== 8) // Address-and-Control-Field-Compression
1781 aflags
|= SESSIONACFC
;
1786 case 28: // last recv lcp confreq
1788 case 26: // Initial Received LCP CONFREQ
1790 case 39: // seq required - we control it as an LNS anyway...
1792 case 36: // Random Vector
1793 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1794 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1795 memcpy(session
[s
].random_vector
, b
, n
);
1796 session
[s
].random_vector_length
= n
;
1799 LOG(2, s
, t
, " Unknown AVP type %d\n", mtype
);
1806 tunnelshutdown(t
, "Unknown Mandatory AVP");
1810 case 1: // SCCRQ - Start Control Connection Request
1812 controlt
*c
= controlnew(2); // sending SCCRP
1813 control16(c
, 2, version
, 1); // protocol version
1814 control32(c
, 3, 3, 1); // framing
1815 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1816 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1817 control16(c
, 9, t
, 1); // assigned tunnel
1818 controladd(c
, t
, s
); // send the resply
1820 tunnel
[t
].state
= TUNNELOPENING
;
1823 tunnel
[t
].state
= TUNNELOPEN
;
1826 tunnel
[t
].state
= TUNNELOPEN
;
1827 controlnull(t
); // ack
1830 controlnull(t
); // ack
1831 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1832 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1835 controlnull(t
); // simply ACK
1849 STAT(session_overflow
);
1850 LOG(1, 0, t
, "No free sessions\n");
1859 sessionfree
= session
[s
].next
;
1860 memset(&session
[s
], 0, sizeof(session
[s
]));
1862 if (s
> config
->cluster_highest_sessionid
)
1863 config
->cluster_highest_sessionid
= s
;
1865 // make a RADIUS session
1866 if (!(r
= radiusnew(s
)))
1868 LOG(1, s
, t
, "No free RADIUS sessions for ICRQ\n");
1869 sessionkill(s
, "no free RADIUS sesions");
1873 c
= controlnew(11); // sending ICRP
1874 session
[s
].id
= sessionid
++;
1875 session
[s
].opened
= time_now
;
1876 session
[s
].tunnel
= t
;
1877 session
[s
].far
= asession
;
1878 session
[s
].last_packet
= time_now
;
1879 LOG(3, s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1880 control16(c
, 14, s
, 1); // assigned session
1881 controladd(c
, t
, s
); // send the reply
1883 // Generate a random challenge
1885 for (n
= 0; n
< 15; n
++)
1886 radius
[r
].auth
[n
] = rand();
1888 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1889 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1890 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1891 STAT(session_created
);
1898 if (amagic
== 0) amagic
= time_now
;
1899 session
[s
].magic
= amagic
; // set magic number
1900 session
[s
].l2tp_flags
= aflags
; // set flags received
1901 LOG(3, s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1902 controlnull(t
); // ack
1903 // In CHAP state, request PAP instead
1908 controlnull(t
); // ack
1909 sessionshutdown(s
, "Closed (Received CDN)");
1912 LOG(1, s
, t
, "Missing message type\n");
1915 STAT(tunnel_rx_errors
);
1916 if (mandatorymessage
& 0x80)
1917 tunnelshutdown(t
, "Unknown message");
1919 LOG(1, s
, t
, "Unknown message type %d\n", message
);
1922 if (chapresponse
) free(chapresponse
);
1923 cluster_send_tunnel(t
);
1927 LOG(4, s
, t
, " Got a ZLB ack\n");
1934 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
1935 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1936 { // HDLC address header, discard
1942 LOG(1, s
, t
, "Short ppp length %d\n", l
);
1943 STAT(tunnel_rx_errors
);
1953 prot
= ntohs(*(uint16_t *) p
);
1958 if (s
&& !session
[s
].opened
) // Is something wrong??
1960 if (!config
->cluster_iam_master
)
1962 // Pass it off to the master to deal with..
1963 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1967 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
1968 STAT(tunnel_rx_errors
);
1974 session
[s
].last_packet
= time_now
;
1975 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1976 processpap(t
, s
, p
, l
);
1978 else if (prot
== PPPCHAP
)
1980 session
[s
].last_packet
= time_now
;
1981 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1982 processchap(t
, s
, p
, l
);
1984 else if (prot
== PPPLCP
)
1986 session
[s
].last_packet
= time_now
;
1987 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1988 processlcp(t
, s
, p
, l
);
1990 else if (prot
== PPPIPCP
)
1992 session
[s
].last_packet
= time_now
;
1993 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1994 processipcp(t
, s
, p
, l
);
1996 else if (prot
== PPPCCP
)
1998 session
[s
].last_packet
= time_now
;
1999 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2000 processccp(t
, s
, p
, l
);
2002 else if (prot
== PPPIP
)
2006 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
2007 return; // closing session, PPP not processed
2010 session
[s
].last_packet
= time_now
;
2011 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2013 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2017 processipin(t
, s
, p
, l
);
2021 STAT(tunnel_rx_errors
);
2022 LOG(1, s
, t
, "Unknown PPP protocol %04X\n", prot
);
2027 // read and process packet on tun
2028 static void processtun(uint8_t * buf
, int len
)
2030 LOG_HEX(5, "Receive TUN Data", buf
, len
);
2031 STAT(tun_rx_packets
);
2032 INC_STAT(tun_rx_bytes
, len
);
2034 CSTAT(call_processtun
);
2040 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
2041 STAT(tun_rx_errors
);
2045 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IP
2046 processipout(buf
, len
);
2051 // Maximum number of actions to complete.
2052 // This is to avoid sending out too many packets
2054 #define MAX_ACTIONS 500
2056 static int regular_cleanups(void)
2058 static sessionidt s
= 0; // Next session to check for actions on.
2062 static clockt next_acct
= 0;
2063 static clockt next_shut_acct
= 0;
2066 LOG(3, 0, 0, "Begin regular cleanup\n");
2068 for (r
= 1; r
< MAXRADIUS
; r
++)
2070 if (!radius
[r
].state
)
2072 if (radius
[r
].retry
)
2074 if (radius
[r
].retry
<= TIME
)
2077 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
2079 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
2081 // check for expired tunnels
2082 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2084 STAT(tunnel_timeout
);
2085 tunnelkill(t
, "Expired");
2088 // check for message resend
2089 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2091 // resend pending messages as timeout on reply
2092 if (tunnel
[t
].retry
<= TIME
)
2094 controlt
*c
= tunnel
[t
].controls
;
2095 uint8_t w
= tunnel
[t
].window
;
2096 tunnel
[t
].try++; // another try
2097 if (tunnel
[t
].try > 5)
2098 tunnelkill(t
, "Timeout on control message"); // game over
2102 tunnelsend(c
->buf
, c
->length
, t
);
2108 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2110 controlt
*c
= controlnew(6); // sending HELLO
2111 controladd(c
, t
, 0); // send the message
2112 LOG(3, 0, t
, "Sending HELLO message\n");
2115 // Check for tunnel changes requested from the CLI
2116 if ((a
= cli_tunnel_actions
[t
].action
))
2118 cli_tunnel_actions
[t
].action
= 0;
2119 if (a
& CLI_TUN_KILL
)
2121 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
2122 tunnelshutdown(t
, "Requested by administrator");
2129 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2132 if (s
> config
->cluster_highest_sessionid
)
2135 if (!session
[s
].opened
) // Session isn't in use
2138 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2140 // IPCP has not completed yet. Resend
2141 LOG(3, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2142 sendipcp(session
[s
].tunnel
, s
);
2145 // check for expired sessions
2146 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2148 sessionkill(s
, "Expired");
2149 if (++count
>= MAX_ACTIONS
) break;
2153 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2154 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2156 sessionshutdown(s
, "No response to LCP ECHO requests");
2157 STAT(session_timeout
);
2158 if (++count
>= MAX_ACTIONS
) break;
2162 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2163 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2165 uint8_t b
[MAXCONTROL
] = {0};
2167 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2171 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
2172 *(uint16_t *)(q
+ 2) = htons(8); // Length
2173 *(uint32_t *)(q
+ 4) = 0; // Magic Number (not supported)
2175 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2176 (int)(time_now
- session
[s
].last_packet
));
2177 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2178 if (++count
>= MAX_ACTIONS
) break;
2181 // Check for actions requested from the CLI
2182 if ((a
= cli_session_actions
[s
].action
))
2186 cli_session_actions
[s
].action
= 0;
2187 if (a
& CLI_SESS_KILL
)
2189 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2190 sessionshutdown(s
, "Requested by administrator");
2191 a
= 0; // dead, no need to check for other actions
2194 if (a
& CLI_SESS_NOSNOOP
)
2196 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2197 session
[s
].snoop_ip
= 0;
2198 session
[s
].snoop_port
= 0;
2201 else if (a
& CLI_SESS_SNOOP
)
2203 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2204 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
2205 cli_session_actions
[s
].snoop_port
);
2207 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2208 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2212 if (a
& CLI_SESS_NOTHROTTLE
)
2214 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2215 throttle_session(s
, 0, 0);
2218 else if (a
& CLI_SESS_THROTTLE
)
2220 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2221 cli_session_actions
[s
].throttle_in
,
2222 cli_session_actions
[s
].throttle_out
);
2224 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2228 if (a
& CLI_SESS_NOFILTER
)
2230 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
2231 filter_session(s
, 0, 0);
2234 else if (a
& CLI_SESS_FILTER
)
2236 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
2237 cli_session_actions
[s
].filter_in
,
2238 cli_session_actions
[s
].filter_out
);
2240 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
2245 cluster_send_session(s
);
2247 if (++count
>= MAX_ACTIONS
) break;
2251 if (*config
->accounting_dir
)
2253 if (next_acct
<= TIME
)
2255 // Dump accounting data
2256 next_acct
= TIME
+ ACCT_TIME
;
2257 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2260 else if (next_shut_acct
<= TIME
)
2262 // Dump accounting data for shutdown sessions
2263 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
2269 if (count
>= MAX_ACTIONS
)
2270 return 1; // Didn't finish!
2272 LOG(3, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count
, config
->cleanup_interval
);
2278 // Are we in the middle of a tunnel update, or radius
2281 static int still_busy(void)
2284 static clockt last_talked
= 0;
2285 static clockt start_busy_wait
= 0;
2286 if (start_busy_wait
== 0)
2287 start_busy_wait
= TIME
;
2289 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2291 if (!tunnel
[i
].controlc
)
2294 if (last_talked
!= TIME
)
2296 LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i
);
2302 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2303 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2305 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2309 for (i
= 1; i
< MAXRADIUS
; i
++)
2311 if (radius
[i
].state
== RADIUSNULL
)
2313 if (radius
[i
].state
== RADIUSWAIT
)
2316 if (last_talked
!= TIME
)
2318 LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2327 static fd_set readset
;
2328 static int readset_n
= 0;
2330 // main loop - gets packets on tun or udp and processes them
2331 static void mainloop(void)
2336 clockt next_cluster_ping
= 0; // send initial ping immediately
2337 time_t next_clean
= time_now
+ config
->cleanup_interval
;
2339 LOG(4, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2340 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2343 FD_SET(udpfd
, &readset
);
2344 FD_SET(tunfd
, &readset
);
2345 FD_SET(controlfd
, &readset
);
2346 FD_SET(clifd
, &readset
);
2347 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2349 if (tunfd
> readset_n
) readset_n
= tunfd
;
2350 if (controlfd
> readset_n
) readset_n
= controlfd
;
2351 if (clifd
> readset_n
) readset_n
= clifd
;
2352 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2354 while (!main_quit
|| still_busy())
2360 int bgp_set
[BGP_NUM_PEERS
];
2363 if (config
->reload_config
)
2365 // Update the config state based on config settings
2369 memcpy(&r
, &readset
, sizeof(fd_set
));
2371 to
.tv_usec
= 100000; // 1/10th of a second.
2375 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2377 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2380 FD_SET(bgp_peers
[i
].sock
, &r
);
2381 if (bgp_peers
[i
].sock
> n
)
2382 n
= bgp_peers
[i
].sock
;
2387 FD_SET(bgp_peers
[i
].sock
, &w
);
2388 if (bgp_peers
[i
].sock
> n
)
2389 n
= bgp_peers
[i
].sock
;
2393 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2395 n
= select(n
+ 1, &r
, 0, 0, &to
);
2398 STAT(select_called
);
2403 if (errno
== EINTR
||
2404 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2407 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2413 struct sockaddr_in addr
;
2417 int cluster_pkts
= 0;
2420 if (FD_ISSET(controlfd
, &r
))
2422 alen
= sizeof(addr
);
2423 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
, alen
);
2428 if (config
->cluster_iam_master
)
2430 for (i
= 0; i
< config
->num_radfds
; i
++)
2432 if (FD_ISSET(radfds
[i
], &r
))
2434 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2441 if (FD_ISSET(clifd
, &r
))
2445 alen
= sizeof(addr
);
2446 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
2452 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
2458 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2460 int isr
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0;
2461 int isw
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0;
2462 bgp_process(&bgp_peers
[i
], isr
, isw
);
2468 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
2471 if (FD_ISSET(udpfd
, &r
))
2473 alen
= sizeof(addr
);
2474 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
2476 processudp(buf
, s
, &addr
);
2487 if (FD_ISSET(tunfd
, &r
))
2489 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
2502 if (FD_ISSET(cluster_sockfd
, &r
))
2504 alen
= sizeof(addr
);
2505 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
2507 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
2512 FD_CLR(cluster_sockfd
, &r
);
2518 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
2519 STAT(multi_read_used
);
2521 if (c
>= config
->multi_read_count
)
2523 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
2524 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
2526 STAT(multi_read_exceeded
);
2530 // Runs on every machine (master and slaves).
2531 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
2533 // Check to see which of the cluster is still alive..
2535 cluster_send_ping(basetime
); // Only does anything if we're a slave
2536 cluster_check_master(); // ditto.
2538 cluster_heartbeat(); // Only does anything if we're a master.
2539 cluster_check_slaves(); // ditto.
2541 master_update_counts(); // If we're a slave, send our byte counters to our master.
2543 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
2544 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
2546 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
2549 // Run token bucket filtering queue..
2550 // Only run it every 1/10th of a second.
2551 // Runs on all machines both master and slave.
2553 static clockt last_run
= 0;
2554 if (last_run
!= TIME
)
2561 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2562 * something to read, else under load this will never actually run....
2565 if (config
->cluster_iam_master
&& next_clean
<= time_now
)
2567 if (regular_cleanups())
2570 next_clean
= time_now
+ 1 ; // Didn't finish. Check quickly.
2574 next_clean
= time_now
+ config
->cleanup_interval
; // Did. Move to next interval.
2579 // Are we the master and shutting down??
2580 if (config
->cluster_iam_master
)
2581 cluster_heartbeat(); // Flush any queued changes..
2583 // Ok. Notify everyone we're shutting down. If we're
2584 // the master, this will force an election.
2585 cluster_send_ping(0);
2588 // Important!!! We MUST not process any packets past this point!
2591 static void stripdomain(char *host
)
2595 if ((p
= strchr(host
, '.')))
2601 FILE *resolv
= fopen("/etc/resolv.conf", "r");
2607 while (fgets(buf
, sizeof(buf
), resolv
))
2609 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
2612 if (!isspace(buf
[6]))
2616 while (isspace(*b
)) b
++;
2621 while (*b
&& !isspace(*b
)) b
++;
2623 if (buf
[0] == 'd') // domain is canonical
2629 // first search line
2632 // hold, may be subsequent domain line
2633 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
2644 int hl
= strlen(host
);
2645 int dl
= strlen(domain
);
2646 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
2647 host
[hl
-dl
- 1] = 0;
2651 *p
= 0; // everything after first dot
2656 // Init data structures
2657 static void initdata(int optdebug
, char *optconfig
)
2661 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
2663 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
2666 if (!(config
= shared_malloc(sizeof(configt
))))
2668 LOG(0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2671 memset(config
, 0, sizeof(configt
));
2672 time(&config
->start_time
);
2673 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
2674 config
->debug
= optdebug
;
2675 config
->num_tbfs
= MAXTBFS
;
2676 config
->rl_rate
= 28; // 28kbps
2678 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
2680 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
2683 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
2685 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
2689 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
2691 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
2695 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
2697 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
2701 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
2703 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
2707 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
2709 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
2712 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
2715 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2717 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2720 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2723 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2725 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2728 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2730 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2732 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2735 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2737 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2738 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2739 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2740 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2742 // Put all the sessions on the free list marked as undefined.
2743 for (i
= 1; i
< MAXSESSION
; i
++)
2745 session
[i
].next
= i
+ 1;
2746 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2748 session
[MAXSESSION
- 1].next
= 0;
2751 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2752 for (i
= 1; i
< MAXTUNNEL
; i
++)
2753 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2757 // Grab my hostname unless it's been specified
2758 gethostname(hostname
, sizeof(hostname
));
2759 stripdomain(hostname
);
2762 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2765 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2767 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2773 static int assign_ip_address(sessionidt s
)
2777 time_t best_time
= time_now
;
2778 char *u
= session
[s
].user
;
2782 CSTAT(call_assign_ip_address
);
2784 for (i
= 1; i
< ip_pool_size
; i
++)
2786 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2789 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2796 if (ip_address_pool
[i
].last
< best_time
)
2799 if (!(best_time
= ip_address_pool
[i
].last
))
2800 break; // never used, grab this one
2806 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2810 session
[s
].ip
= ip_address_pool
[best
].address
;
2811 session
[s
].ip_pool_index
= best
;
2812 ip_address_pool
[best
].assigned
= 1;
2813 ip_address_pool
[best
].last
= time_now
;
2814 ip_address_pool
[best
].session
= s
;
2815 if (session
[s
].walled_garden
)
2816 /* Don't track addresses of users in walled garden (note: this
2817 means that their address isn't "sticky" even if they get
2819 ip_address_pool
[best
].user
[0] = 0;
2821 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2824 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
2825 reuse
? "Reusing" : "Allocating", best
);
2830 static void free_ip_address(sessionidt s
)
2832 int i
= session
[s
].ip_pool_index
;
2835 CSTAT(call_free_ip_address
);
2838 return; // what the?
2840 if (i
< 0) // Is this actually part of the ip pool?
2844 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2846 ip_address_pool
[i
].assigned
= 0;
2847 ip_address_pool
[i
].session
= 0;
2848 ip_address_pool
[i
].last
= time_now
;
2852 // Fsck the address pool against the session table.
2853 // Normally only called when we become a master.
2855 // This isn't perfect: We aren't keep tracking of which
2856 // users used to have an IP address.
2858 void rebuild_address_pool(void)
2863 // Zero the IP pool allocation, and build
2864 // a map from IP address to pool index.
2865 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2867 ip_address_pool
[i
].assigned
= 0;
2868 ip_address_pool
[i
].session
= 0;
2869 if (!ip_address_pool
[i
].address
)
2872 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2875 for (i
= 0; i
< MAXSESSION
; ++i
)
2878 if (!(session
[i
].opened
&& session
[i
].ip
))
2880 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2882 if (session
[i
].ip_pool_index
< 0)
2884 // Not allocated out of the pool.
2885 if (ipid
< 1) // Not found in the pool either? good.
2888 LOG(0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2889 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
2891 // Fall through and process it as part of the pool.
2895 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2897 LOG(0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2899 session
[i
].ip_pool_index
= ipid
;
2903 ip_address_pool
[ipid
].assigned
= 1;
2904 ip_address_pool
[ipid
].session
= i
;
2905 ip_address_pool
[ipid
].last
= time_now
;
2906 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2907 session
[i
].ip_pool_index
= ipid
;
2908 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
2913 // Fix the address pool to match a changed session.
2914 // (usually when the master sends us an update).
2915 static void fix_address_pool(int sid
)
2919 ipid
= session
[sid
].ip_pool_index
;
2921 if (ipid
> ip_pool_size
)
2922 return; // Ignore it. rebuild_address_pool will fix it up.
2924 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
2925 return; // Just ignore it. rebuild_address_pool will take care of it.
2927 ip_address_pool
[ipid
].assigned
= 1;
2928 ip_address_pool
[ipid
].session
= sid
;
2929 ip_address_pool
[ipid
].last
= time_now
;
2930 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2934 // Add a block of addresses to the IP pool to hand out.
2936 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
2940 mask
= 0xffffffff; // Host route only.
2944 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
2947 for (i
= addr
;(i
& mask
) == addr
; ++i
)
2949 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
2950 continue; // Skip 0 and broadcast addresses.
2952 ip_address_pool
[ip_pool_size
].address
= i
;
2953 ip_address_pool
[ip_pool_size
].assigned
= 0;
2955 if (ip_pool_size
>= MAXIPPOOL
)
2957 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
2963 // Initialize the IP address pool
2964 static void initippool()
2969 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2971 if (!(f
= fopen(IPPOOLFILE
, "r")))
2973 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2977 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2980 buf
[4095] = 0; // Force it to be zero terminated/
2982 if (*buf
== '#' || *buf
== '\n')
2983 continue; // Skip comments / blank lines
2984 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2985 if ((p
= (char *)strchr(buf
, ':')))
2989 src
= inet_addr(buf
);
2990 if (src
== INADDR_NONE
)
2992 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
2995 // This entry is for a specific IP only
2996 if (src
!= config
->bind_address
)
3001 if ((p
= (char *)strchr(pool
, '/')))
3005 in_addr_t start
= 0, mask
= 0;
3007 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
3009 if (!*p
|| !(numbits
= atoi(p
)))
3011 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
3014 start
= ntohl(inet_addr(pool
));
3015 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
3017 // Add a static route for this pool
3018 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
3019 fmtaddr(htonl(start
), 0), 32 + mask
);
3021 routeset(0, start
, mask
, 0, 1);
3023 add_to_ip_pool(start
, mask
);
3027 // It's a single ip address
3028 add_to_ip_pool(inet_addr(pool
), 0);
3032 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
3035 void snoop_send_packet(char *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
3037 struct sockaddr_in snoop_addr
= {0};
3038 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
3041 snoop_addr
.sin_family
= AF_INET
;
3042 snoop_addr
.sin_addr
.s_addr
= destination
;
3043 snoop_addr
.sin_port
= ntohs(port
);
3045 LOG(5, 0, 0, "Snooping %d byte packet to %s:%d\n", size
,
3046 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
3047 htons(snoop_addr
.sin_port
));
3049 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
3050 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
3052 STAT(packets_snooped
);
3055 static int dump_session(FILE **f
, sessiont
*s
)
3057 if (!s
->opened
|| !s
->ip
|| !(s
->cin
|| s
->cout
) || !*s
->user
|| s
->walled_garden
)
3062 char filename
[1024];
3064 time_t now
= time(NULL
);
3066 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
3067 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
3069 if (!(*f
= fopen(filename
, "w")))
3071 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
3075 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
3076 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
3080 "# format: username ip qos uptxoctets downrxoctets\n",
3086 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
3087 fprintf(*f
, "%s %s %d %u %u\n",
3088 s
->user
, // username
3089 fmtaddr(htonl(s
->ip
), 0), // ip
3090 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
3091 (uint32_t) s
->cin
, // uptxoctets
3092 (uint32_t) s
->cout
); // downrxoctets
3094 s
->pin
= s
->cin
= 0;
3095 s
->pout
= s
->cout
= 0;
3100 static void dump_acct_info(int all
)
3106 CSTAT(call_dump_acct_info
);
3110 for (i
= 0; i
< shut_acct_n
; i
++)
3111 dump_session(&f
, &shut_acct
[i
]);
3117 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3118 dump_session(&f
, &session
[i
]);
3125 int main(int argc
, char *argv
[])
3129 char *optconfig
= CONFIGFILE
;
3131 time(&basetime
); // start clock
3134 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
3139 if (fork()) exit(0);
3141 freopen("/dev/null", "r", stdin
);
3142 freopen("/dev/null", "w", stdout
);
3143 freopen("/dev/null", "w", stderr
);
3152 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
3155 printf("Args are:\n"
3156 "\t-d\t\tDetach from terminal\n"
3157 "\t-c <file>\tConfig file\n"
3158 "\t-h <hostname>\tForce hostname\n"
3166 // Start the timer routine off
3168 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3169 signal(SIGALRM
, sigalrm_handler
);
3170 siginterrupt(SIGALRM
, 0);
3173 initdata(optdebug
, optconfig
);
3177 init_tbf(config
->num_tbfs
);
3179 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
3180 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005 Optus Internet Engineering\n");
3181 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3184 rlim
.rlim_cur
= RLIM_INFINITY
;
3185 rlim
.rlim_max
= RLIM_INFINITY
;
3186 // Remove the maximum core size
3187 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
3188 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
3190 // Make core dumps go to /tmp
3194 if (config
->scheduler_fifo
)
3197 struct sched_param params
= {0};
3198 params
.sched_priority
= 1;
3200 if (get_nprocs() < 2)
3202 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3203 config
->scheduler_fifo
= 0;
3207 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3209 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3213 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3214 config
->scheduler_fifo
= 0;
3219 /* Set up the cluster communications port. */
3220 if (cluster_init() < 0)
3224 signal(SIGPIPE
, SIG_IGN
);
3225 bgp_setup(config
->as_number
);
3226 bgp_add_route(config
->bind_address
, 0xffffffff);
3227 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3229 if (config
->neighbour
[i
].name
[0])
3230 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3231 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3232 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3237 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3245 signal(SIGHUP
, sighup_handler
);
3246 signal(SIGTERM
, sigterm_handler
);
3247 signal(SIGINT
, sigterm_handler
);
3248 signal(SIGQUIT
, sigquit_handler
);
3249 signal(SIGCHLD
, sigchild_handler
);
3251 // Prevent us from getting paged out
3252 if (config
->lock_pages
)
3254 if (!mlockall(MCL_CURRENT
))
3255 LOG(1, 0, 0, "Locking pages into memory\n");
3257 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3262 // Drop privileges here
3263 if (config
->target_uid
> 0 && geteuid() == 0)
3264 setuid(config
->target_uid
);
3269 /* try to shut BGP down cleanly; with luck the sockets will be
3270 writable since we're out of the select */
3271 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3272 if (bgp_peers
[i
].state
== Established
)
3273 bgp_stop(&bgp_peers
[i
]);
3276 /* remove plugins (so cleanup code gets run) */
3279 // Remove the PID file if we wrote it
3280 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3281 unlink(config
->pid_file
);
3283 /* kill CLI children */
3284 signal(SIGTERM
, SIG_IGN
);
3289 static void sighup_handler(int sig
)
3291 if (log_stream
&& log_stream
!= stderr
)
3300 static void sigalrm_handler(int sig
)
3302 // Log current traffic stats
3304 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3305 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3306 (udp_rx
/ 1024.0 / 1024.0 * 8),
3307 (eth_tx
/ 1024.0 / 1024.0 * 8),
3308 (eth_rx
/ 1024.0 / 1024.0 * 8),
3309 (udp_tx
/ 1024.0 / 1024.0 * 8),
3310 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3311 udp_rx_pkt
, eth_rx_pkt
);
3313 udp_tx
= udp_rx
= 0;
3314 udp_rx_pkt
= eth_rx_pkt
= 0;
3315 eth_tx
= eth_rx
= 0;
3317 if (config
->dump_speed
)
3318 printf("%s\n", config
->bandwidth
);
3320 // Update the internal time counter
3322 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3327 struct param_timer p
= { time_now
};
3328 run_plugins(PLUGIN_TIMER
, &p
);
3333 static void sigterm_handler(int sig
)
3335 LOG(1, 0, 0, "Shutting down cleanly\n");
3336 if (config
->save_state
)
3342 static void sigquit_handler(int sig
)
3346 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3348 if (config
->cluster_iam_master
)
3350 for (i
= 1; i
< MAXSESSION
; i
++)
3352 if (session
[i
].opened
)
3353 sessionkill(i
, "L2TPNS Closing");
3355 for (i
= 1; i
< MAXTUNNEL
; i
++)
3357 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3358 tunnelshutdown(i
, "L2TPNS Closing");
3365 static void sigchild_handler(int sig
)
3367 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3371 static void read_state()
3377 char magic
[sizeof(DUMP_MAGIC
) - 1];
3380 if (!config
->save_state
)
3386 if (stat(STATEFILE
, &sb
) < 0)
3392 if (sb
.st_mtime
< (time(NULL
) - 60))
3394 LOG(0, 0, 0, "State file is too old to read, ignoring\n");
3399 f
= fopen(STATEFILE
, "r");
3404 LOG(0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3408 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3410 LOG(0, 0, 0, "Bad state file magic\n");
3414 LOG(1, 0, 0, "Reading state information\n");
3415 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3417 LOG(0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3421 if (buf
[0] > ip_pool_size
)
3423 LOG(0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3427 LOG(2, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3428 for (i
= 0; i
< buf
[0]; i
++)
3430 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3432 LOG(0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3436 if (itmp
.address
!= ip_address_pool
[i
].address
)
3438 LOG(0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3442 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3445 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3447 LOG(0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3451 LOG(2, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3452 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3454 LOG(0, 0, 0, "Error reading tunnel data from state file\n");
3458 for (i
= 0; i
< MAXTUNNEL
; i
++)
3460 tunnel
[i
].controlc
= 0;
3461 tunnel
[i
].controls
= NULL
;
3462 tunnel
[i
].controle
= NULL
;
3463 if (*tunnel
[i
].hostname
)
3464 LOG(3, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3467 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3469 LOG(0, 0, 0, "Error/mismatch reading session header from state file\n");
3473 LOG(2, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3474 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3476 LOG(0, 0, 0, "Error reading session data from state file\n");
3480 for (i
= 0; i
< MAXSESSION
; i
++)
3482 session
[i
].tbf_in
= 0;
3483 session
[i
].tbf_out
= 0;
3484 if (session
[i
].opened
)
3486 LOG(2, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3488 sessionsetup(session
[i
].tunnel
, i
);
3493 LOG(0, 0, 0, "Loaded saved state information\n");
3496 static void dump_state()
3501 if (!config
->save_state
)
3506 if (!(f
= fopen(STATEFILE
, "w")))
3509 LOG(1, 0, 0, "Dumping state information\n");
3511 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3514 LOG(2, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3515 buf
[0] = ip_pool_size
;
3516 buf
[1] = sizeof(ippoolt
);
3517 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3519 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3522 LOG(2, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3524 buf
[1] = sizeof(tunnelt
);
3525 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3527 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3530 LOG(2, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3531 buf
[0] = MAXSESSION
;
3532 buf
[1] = sizeof(sessiont
);
3533 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3535 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3543 LOG(0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3547 static void build_chap_response(char *challenge
, uint8_t id
, uint16_t challenge_length
, char **challenge_response
)
3550 *challenge_response
= NULL
;
3552 if (!*config
->l2tpsecret
)
3554 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3558 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
3560 *challenge_response
= (char *)calloc(17, 1);
3563 MD5Update(&ctx
, &id
, 1);
3564 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3565 MD5Update(&ctx
, challenge
, challenge_length
);
3566 MD5Final(*challenge_response
, &ctx
);
3571 static int facility_value(char *name
)
3574 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3576 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3577 return facilitynames
[i
].c_val
;
3582 static void update_config()
3585 static int timeout
= 0;
3586 static int interval
= 0;
3596 if (*config
->log_filename
)
3598 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3600 char *p
= config
->log_filename
+ 7;
3603 openlog("l2tpns", LOG_PID
, facility_value(p
));
3607 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3609 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3611 fseek(log_stream
, 0, SEEK_END
);
3612 setbuf(log_stream
, NULL
);
3616 log_stream
= stderr
;
3617 setbuf(log_stream
, NULL
);
3623 log_stream
= stderr
;
3624 setbuf(log_stream
, NULL
);
3629 config
->numradiusservers
= 0;
3630 for (i
= 0; i
< MAXRADSERVER
; i
++)
3631 if (config
->radiusserver
[i
])
3633 config
->numradiusservers
++;
3634 // Set radius port: if not set, take the port from the
3635 // first radius server. For the first radius server,
3636 // take the #defined default value from l2tpns.h
3638 // test twice, In case someone works with
3639 // a secondary radius server without defining
3640 // a primary one, this will work even then.
3641 if (i
>0 && !config
->radiusport
[i
])
3642 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3643 if (!config
->radiusport
[i
])
3644 config
->radiusport
[i
] = RADPORT
;
3647 if (!config
->numradiusservers
)
3648 LOG(0, 0, 0, "No RADIUS servers defined!\n");
3650 config
->num_radfds
= 2 << RADIUS_SHIFT
;
3653 for (i
= 0; i
< MAXPLUGINS
; i
++)
3655 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3658 if (*config
->plugins
[i
])
3661 add_plugin(config
->plugins
[i
]);
3663 else if (*config
->old_plugins
[i
])
3666 remove_plugin(config
->old_plugins
[i
]);
3669 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3670 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
3671 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3672 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3673 if (!*config
->cluster_interface
)
3674 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3676 if (!config
->cluster_hb_interval
)
3677 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3679 if (!config
->cluster_hb_timeout
)
3680 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3682 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3684 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3685 // late, ensure we're sufficiently larger than that
3686 int t
= 4 * config
->cluster_hb_interval
+ 11;
3688 if (config
->cluster_hb_timeout
< t
)
3690 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3691 config
->cluster_hb_timeout
= t
;
3694 // Push timing changes to the slaves immediately if we're the master
3695 if (config
->cluster_iam_master
)
3696 cluster_heartbeat();
3698 interval
= config
->cluster_hb_interval
;
3699 timeout
= config
->cluster_hb_timeout
;
3703 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3706 if ((f
= fopen(config
->pid_file
, "w")))
3708 fprintf(f
, "%d\n", getpid());
3710 config
->wrote_pid
= 1;
3714 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3718 config
->reload_config
= 0;
3721 static void read_config_file()
3725 if (!config
->config_file
) return;
3726 if (!(f
= fopen(config
->config_file
, "r")))
3728 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3732 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
3734 LOG(3, 0, 0, "Done reading config file\n");
3739 int sessionsetup(tunnelidt t
, sessionidt s
)
3741 // A session now exists, set it up
3747 CSTAT(call_sessionsetup
);
3749 LOG(3, s
, t
, "Doing session setup for session\n");
3753 assign_ip_address(s
);
3756 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3757 sessionshutdown(s
, "No IP addresses available");
3760 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
3761 fmtaddr(htonl(session
[s
].ip
), 0));
3765 // Make sure this is right
3766 session
[s
].tunnel
= t
;
3768 // zap old sessions with same IP and/or username
3769 // Don't kill gardened sessions - doing so leads to a DoS
3770 // from someone who doesn't need to know the password
3773 user
= session
[s
].user
;
3774 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3776 if (i
== s
) continue;
3777 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3778 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3779 sessionkill(i
, "Duplicate session for users");
3786 // Add the route for this session.
3787 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3789 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
3790 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
3793 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
3796 // Static IPs need to be routed if not already
3797 // convered by a Framed-Route. Anything else is part
3798 // of the IP address pool and is already routed, it
3799 // just needs to be added to the IP cache.
3800 if (session
[s
].ip_pool_index
== -1) // static ip
3802 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
3805 cache_ipmap(session
[s
].ip
, s
);
3808 if (!session
[s
].unique_id
)
3810 // did this session just finish radius?
3811 LOG(3, s
, t
, "Sending initial IPCP to client\n");
3813 session
[s
].unique_id
= ++last_id
;
3816 // Run the plugin's against this new session.
3818 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3819 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3822 // Allocate TBFs if throttled
3823 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3824 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3826 session
[s
].last_packet
= time_now
;
3828 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
3829 fmtaddr(htonl(session
[s
].ip
), 0),
3830 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
3832 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3834 return 1; // RADIUS OK and IP allocated, done...
3838 // This session just got dropped on us by the master or something.
3839 // Make sure our tables up up to date...
3841 int load_session(sessionidt s
, sessiont
*new)
3847 if (new->ip_pool_index
>= MAXIPPOOL
||
3848 new->tunnel
>= MAXTUNNEL
)
3850 LOG(0, s
, 0, "Strange session update received!\n");
3851 // FIXME! What to do here?
3856 // Ok. All sanity checks passed. Now we're committed to
3857 // loading the new session.
3860 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3862 // See if routes/ip cache need updating
3863 if (new->ip
!= session
[s
].ip
)
3866 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3867 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
3868 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
3876 // remove old routes...
3877 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3879 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
3880 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
3883 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
3889 if (session
[s
].ip_pool_index
== -1) // static IP
3891 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
3893 else // It's part of the IP pool, remove it manually.
3894 uncache_ipmap(session
[s
].ip
);
3899 // add new routes...
3900 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
3902 if ((new->ip
& new->route
[i
].mask
) ==
3903 (new->route
[i
].ip
& new->route
[i
].mask
))
3906 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
3912 // If there's a new one, add it.
3913 if (new->ip_pool_index
== -1)
3915 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
3918 cache_ipmap(new->ip
, s
);
3923 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
3925 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %d\n", (int) new->filter_in
);
3929 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
3931 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %d\n", (int) new->filter_out
);
3932 new->filter_out
= 0;
3935 if (new->filter_in
!= session
[s
].filter_in
)
3937 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
3938 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
3941 if (new->filter_out
!= session
[s
].filter_out
)
3943 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
3944 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
3947 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
3948 // for walking the sessions to forward byte counts to the master.
3949 config
->cluster_highest_sessionid
= s
;
3951 // TEMP: old session struct used a uint32_t to define the throttle
3952 // speed for both up/down, new uses a uint16_t for each. Deal with
3953 // sessions from an old master for migration.
3954 if (new->throttle_out
== 0 && new->tbf_out
)
3955 new->throttle_out
= new->throttle_in
;
3957 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
3959 // Do fixups into address pool.
3960 if (new->ip_pool_index
!= -1)
3961 fix_address_pool(s
);
3966 static void initplugins()
3970 loaded_plugins
= ll_init();
3971 // Initialize the plugins to nothing
3972 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
3973 plugins
[i
] = ll_init();
3976 static void *open_plugin(char *plugin_name
, int load
)
3978 char path
[256] = "";
3980 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
3981 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
3982 return dlopen(path
, RTLD_NOW
);
3985 // plugin callback to get a config value
3986 static void *getconfig(char *key
, enum config_typet type
)
3990 for (i
= 0; config_values
[i
].key
; i
++)
3992 if (!strcmp(config_values
[i
].key
, key
))
3994 if (config_values
[i
].type
== type
)
3995 return ((void *) config
) + config_values
[i
].offset
;
3997 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
3998 key
, type
, config_values
[i
].type
);
4004 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
4008 static int add_plugin(char *plugin_name
)
4010 static struct pluginfuncs funcs
= {
4015 sessiontbysessionidt
,
4016 sessionidtbysessiont
,
4022 cluster_send_session
,
4025 void *p
= open_plugin(plugin_name
, 1);
4026 int (*initfunc
)(struct pluginfuncs
*);
4031 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
4035 if (ll_contains(loaded_plugins
, p
))
4038 return 0; // already loaded
4042 int *v
= dlsym(p
, "plugin_api_version");
4043 if (!v
|| *v
!= PLUGIN_API_VERSION
)
4045 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
4051 if ((initfunc
= dlsym(p
, "plugin_init")))
4053 if (!initfunc(&funcs
))
4055 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
4061 ll_push(loaded_plugins
, p
);
4063 for (i
= 0; i
< max_plugin_functions
; i
++)
4066 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4068 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
4069 ll_push(plugins
[i
], x
);
4073 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
4077 static void run_plugin_done(void *plugin
)
4079 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
4085 static int remove_plugin(char *plugin_name
)
4087 void *p
= open_plugin(plugin_name
, 0);
4093 if (ll_contains(loaded_plugins
, p
))
4096 for (i
= 0; i
< max_plugin_functions
; i
++)
4099 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
4100 ll_delete(plugins
[i
], x
);
4103 ll_delete(loaded_plugins
, p
);
4109 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
4113 int run_plugins(int plugin_type
, void *data
)
4115 int (*func
)(void *data
);
4117 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
4118 return PLUGIN_RET_ERROR
;
4120 ll_reset(plugins
[plugin_type
]);
4121 while ((func
= ll_next(plugins
[plugin_type
])))
4125 if (r
!= PLUGIN_RET_OK
)
4126 return r
; // stop here
4129 return PLUGIN_RET_OK
;
4132 static void plugins_done()
4136 ll_reset(loaded_plugins
);
4137 while ((p
= ll_next(loaded_plugins
)))
4141 static void processcontrol(uint8_t * buf
, int len
, struct sockaddr_in
*addr
, int alen
)
4143 struct nsctl request
;
4144 struct nsctl response
;
4145 int type
= unpack_control(&request
, buf
, len
);
4149 if (log_stream
&& config
->debug
>= 4)
4153 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4154 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
4158 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4159 dump_control(&request
, log_stream
);
4165 case NSCTL_REQ_LOAD
:
4166 if (request
.argc
!= 1)
4168 response
.type
= NSCTL_RES_ERR
;
4170 response
.argv
[0] = "name of plugin required";
4172 else if ((r
= add_plugin(request
.argv
[0])) < 1)
4174 response
.type
= NSCTL_RES_ERR
;
4176 response
.argv
[0] = !r
4177 ? "plugin already loaded"
4178 : "error loading plugin";
4182 response
.type
= NSCTL_RES_OK
;
4188 case NSCTL_REQ_UNLOAD
:
4189 if (request
.argc
!= 1)
4191 response
.type
= NSCTL_RES_ERR
;
4193 response
.argv
[0] = "name of plugin required";
4195 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
4197 response
.type
= NSCTL_RES_ERR
;
4199 response
.argv
[0] = !r
4200 ? "plugin not loaded"
4201 : "plugin not found";
4205 response
.type
= NSCTL_RES_OK
;
4211 case NSCTL_REQ_HELP
:
4212 response
.type
= NSCTL_RES_OK
;
4215 ll_reset(loaded_plugins
);
4216 while ((p
= ll_next(loaded_plugins
)))
4218 char **help
= dlsym(p
, "plugin_control_help");
4219 while (response
.argc
< 0xff && help
&& *help
)
4220 response
.argv
[response
.argc
++] = *help
++;
4225 case NSCTL_REQ_CONTROL
:
4227 struct param_control param
= {
4228 config
->cluster_iam_master
,
4235 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4237 if (r
== PLUGIN_RET_ERROR
)
4239 response
.type
= NSCTL_RES_ERR
;
4241 response
.argv
[0] = param
.additional
4243 : "error returned by plugin";
4245 else if (r
== PLUGIN_RET_NOTMASTER
)
4247 static char msg
[] = "must be run on master: 000.000.000.000";
4249 response
.type
= NSCTL_RES_ERR
;
4251 if (config
->cluster_master_address
)
4253 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
4254 response
.argv
[0] = msg
;
4258 response
.argv
[0] = "must be run on master: none elected";
4261 else if (!(param
.response
& NSCTL_RESPONSE
))
4263 response
.type
= NSCTL_RES_ERR
;
4265 response
.argv
[0] = param
.response
4266 ? "unrecognised response value from plugin"
4267 : "unhandled action";
4271 response
.type
= param
.response
;
4273 if (param
.additional
)
4276 response
.argv
[0] = param
.additional
;
4284 response
.type
= NSCTL_RES_ERR
;
4286 response
.argv
[0] = "error unpacking control packet";
4289 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4292 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4296 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4299 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4300 if (log_stream
&& config
->debug
>= 4)
4302 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4303 dump_control(&response
, log_stream
);
4307 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4308 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
4313 static tunnelidt
new_tunnel()
4316 for (i
= 1; i
< MAXTUNNEL
; i
++)
4318 if (tunnel
[i
].state
== TUNNELFREE
)
4320 LOG(4, 0, i
, "Assigning tunnel ID %d\n", i
);
4321 if (i
> config
->cluster_highest_tunnelid
)
4322 config
->cluster_highest_tunnelid
= i
;
4326 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4331 // We're becoming the master. Do any required setup..
4333 // This is principally telling all the plugins that we're
4334 // now a master, and telling them about all the sessions
4335 // that are active too..
4337 void become_master(void)
4340 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4342 // running a bunch of iptables commands is slow and can cause
4343 // the master to drop tunnels on takeover--kludge around the
4344 // problem by forking for the moment (note: race)
4345 if (!fork_and_close())
4347 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4349 if (!session
[s
].opened
) // Not an in-use session.
4352 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4358 for (i
= 0; i
< config
->num_radfds
; i
++)
4360 FD_SET(radfds
[i
], &readset
);
4361 if (radfds
[i
] > readset_n
)
4362 readset_n
= radfds
[i
];
4366 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4372 if (CLI_HELP_REQUESTED
)
4373 return CLI_HELP_NO_ARGS
;
4376 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4378 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4381 if (!session
[s
].opened
)
4384 idle
= time_now
- session
[s
].last_packet
;
4385 idle
/= 5 ; // In multiples of 5 seconds.
4395 for (i
= 0; i
< 63; ++i
)
4397 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4399 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4400 cli_print(cli
, "%d total sessions open.", count
);
4404 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4410 if (CLI_HELP_REQUESTED
)
4411 return CLI_HELP_NO_ARGS
;
4414 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4416 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4419 if (!session
[s
].opened
)
4422 d
= time_now
- session
[s
].opened
;
4425 while (d
> 1 && open
< 32)
4435 for (i
= 0; i
< 30; ++i
)
4437 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4440 cli_print(cli
, "%d total sessions open.", count
);
4446 * This unencodes the AVP using the L2TP CHAP secret and the
4447 * previously stored random vector. It replaces the hidden data with
4448 * the cleartext data and returns the length of the cleartext data
4449 * (including the AVP "header" of 6 bytes).
4451 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4453 static int unhide_avp(uint8_t *avp
, tunnelidt t
, sessionidt s
, uint16_t length
)
4458 uint8_t working_vector
[16];
4459 uint16_t hidden_length
;
4464 // Find the AVP type.
4465 type
[0] = *(avp
+ 4);
4466 type
[1] = *(avp
+ 5);
4468 // Line up with the hidden data
4469 cursor
= output
= avp
+ 6;
4471 // Compute initial pad
4473 MD5Update(&ctx
, type
, 2);
4474 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4475 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4476 MD5Final(digest
, &ctx
);
4478 // Get hidden length
4479 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4481 // Keep these for later use
4482 working_vector
[0] = *cursor
;
4483 working_vector
[1] = *(cursor
+ 1);
4486 if (hidden_length
> length
- 8)
4488 LOG(1, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4492 /* Decrypt remainder */
4494 todo
= hidden_length
;
4497 working_vector
[done
] = *cursor
;
4498 *output
= digest
[done
] ^ *cursor
;
4503 if (done
== 16 && todo
)
4505 // Compute new digest
4508 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4509 MD5Update(&ctx
, &working_vector
, 16);
4510 MD5Final(digest
, &ctx
);
4514 return hidden_length
+ 6;
4517 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
4521 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
4522 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
4523 case FILTER_PORT_OP_GT
: return port
> p
->port
;
4524 case FILTER_PORT_OP_LT
: return port
< p
->port
;
4525 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
4531 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
4535 case FILTER_FLAG_OP_ANY
:
4536 return (flags
& sflags
) || (~flags
& cflags
);
4538 case FILTER_FLAG_OP_ALL
:
4539 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
4541 case FILTER_FLAG_OP_EST
:
4542 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
4548 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
4550 uint16_t frag_offset
;
4554 uint16_t src_port
= 0;
4555 uint16_t dst_port
= 0;
4557 ip_filter_rulet
*rule
;
4559 if (len
< 20) // up to end of destination address
4562 if ((*buf
>> 4) != 4) // IPv4
4565 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
4567 src_ip
= *(in_addr_t
*) (buf
+ 12);
4568 dst_ip
= *(in_addr_t
*) (buf
+ 16);
4570 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
4572 int l
= (buf
[0] & 0xf) * 4; // length of IP header
4573 if (len
< l
+ 4) // ports
4576 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
4577 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
4578 if (proto
== IPPROTO_TCP
)
4580 if (len
< l
+ 14) // flags
4583 flags
= buf
[l
+ 13] & 0x3f;
4587 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
4589 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
4592 if (rule
->src_wild
!= INADDR_BROADCAST
&&
4593 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
4596 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
4597 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
4602 if (!rule
->frag
|| rule
->action
== FILTER_ACTION_DENY
)
4610 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
4612 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
4615 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
4618 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
4619 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
4626 return rule
->action
== FILTER_ACTION_PERMIT
;