3 // Copyright (c) 2003, 2004 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
7 char const *cvs_id_l2tpns
= "$Id: l2tpns.c,v 1.63 2004-12-09 00:50:45 bodea Exp $";
13 #include <linux/if_tun.h>
18 #include <net/route.h>
21 #include <netinet/in.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
31 #include <sys/resource.h>
39 #include <sys/sysinfo.h>
47 #include "constants.h"
57 configt
*config
= NULL
; // all configuration
58 int tunfd
= -1; // tun interface file handle. (network device)
59 int udpfd
= -1; // UDP file handle
60 int controlfd
= -1; // Control signal handle
61 int clifd
= -1; // Socket listening for CLI connections.
62 int snoopfd
= -1; // UDP file handle for sending out intercept data
63 int *radfds
= NULL
; // RADIUS requests file handles
64 int ifrfd
= -1; // File descriptor for routing, etc
65 time_t basetime
= 0; // base clock
66 char hostname
[1000] = ""; // us.
67 static u32 sessionid
= 0; // session id for radius accounting
68 static int syslog_log
= 0; // are we logging to syslog
69 static FILE *log_stream
= NULL
; // file handle for direct logging (i.e. direct into file, not via syslog).
70 extern int cluster_sockfd
; // Intra-cluster communications socket.
71 u32 last_id
= 0; // Last used PPP SID. Can I kill this?? -- mo
73 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
74 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
76 static void *ip_hash
[256]; // Mapping from IP address to session structures.
79 static u32 udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
80 static u32 eth_rx
= 0, eth_rx_pkt
= 0;
83 static u32 ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
84 time_t time_now
= 0; // Current time in seconds since epoch.
85 static char time_now_string
[64] = {0}; // Current time as a string.
86 static char main_quit
= 0; // True if we're in the process of exiting.
87 linked_list
*loaded_plugins
;
88 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
90 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
91 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
93 config_descriptt config_values
[] = {
94 CONFIG("debug", debug
, INT
),
95 CONFIG("log_file", log_filename
, STRING
),
96 CONFIG("pid_file", pid_file
, STRING
),
97 CONFIG("l2tp_secret", l2tpsecret
, STRING
),
98 CONFIG("primary_dns", default_dns1
, IP
),
99 CONFIG("secondary_dns", default_dns2
, IP
),
100 CONFIG("save_state", save_state
, BOOL
),
101 CONFIG("primary_radius", radiusserver
[0], IP
),
102 CONFIG("secondary_radius", radiusserver
[1], IP
),
103 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
104 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
105 CONFIG("radius_accounting", radius_accounting
, BOOL
),
106 CONFIG("radius_secret", radiussecret
, STRING
),
107 CONFIG("bind_address", bind_address
, IP
),
108 CONFIG("peer_address", peer_address
, IP
),
109 CONFIG("send_garp", send_garp
, BOOL
),
110 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
111 CONFIG("throttle_buckets", num_tbfs
, INT
),
112 CONFIG("accounting_dir", accounting_dir
, STRING
),
113 CONFIG("setuid", target_uid
, INT
),
114 CONFIG("dump_speed", dump_speed
, BOOL
),
115 CONFIG("cleanup_interval", cleanup_interval
, INT
),
116 CONFIG("multi_read_count", multi_read_count
, INT
),
117 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
118 CONFIG("lock_pages", lock_pages
, BOOL
),
119 CONFIG("icmp_rate", icmp_rate
, INT
),
120 CONFIG("cluster_address", cluster_address
, IP
),
121 CONFIG("cluster_interface", cluster_interface
, STRING
),
122 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
123 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
127 static char *plugin_functions
[] = {
134 "plugin_new_session",
135 "plugin_kill_session",
137 "plugin_radius_response",
138 "plugin_become_master",
139 "plugin_new_session_master",
142 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
144 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
145 sessiont
*session
= NULL
; // Array of session structures.
146 sessioncountt
*sess_count
= NULL
; // Array of partial per-session traffic counters.
147 radiust
*radius
= NULL
; // Array of radius structures.
148 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
149 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
150 static controlt
*controlfree
= 0;
151 struct Tstats
*_statistics
= NULL
;
153 struct Tringbuffer
*ringbuffer
= NULL
;
156 static void cache_ipmap(ipt ip
, int s
);
157 static void uncache_ipmap(ipt ip
);
158 static void free_ip_address(sessionidt s
);
159 static void dump_acct_info(void);
160 static void sighup_handler(int sig
);
161 static void sigalrm_handler(int sig
);
162 static void sigterm_handler(int sig
);
163 static void sigquit_handler(int sig
);
164 static void sigchild_handler(int sig
);
165 static void read_state(void);
166 static void dump_state(void);
167 static void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
);
168 static void update_config(void);
169 static void read_config_file(void);
170 static void initplugins(void);
171 static int add_plugin(char *plugin_name
);
172 static int remove_plugin(char *plugin_name
);
173 static void plugins_done(void);
174 static void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
, int alen
);
175 static tunnelidt
new_tunnel(void);
176 static int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
);
178 // return internal time (10ths since process startup)
179 static clockt
now(void)
183 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
186 // work out a retry time based on try number
187 // This is a straight bounded exponential backoff.
188 // Maximum re-try time is 32 seconds. (2^5).
189 clockt
backoff(u8
try)
191 if (try > 5) try = 5; // max backoff
192 return now() + 10 * (1 << try);
197 // Log a debug message. Typically called via the LOG macro
199 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
201 static char message
[65536] = {0};
202 static char message2
[65536] = {0};
208 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
209 ringbuffer
->tail
= 0;
210 if (ringbuffer
->tail
== ringbuffer
->head
)
211 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
212 ringbuffer
->head
= 0;
214 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
215 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
216 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
217 va_start(ap
, format
);
218 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
223 if (config
->debug
< level
) return;
225 va_start(ap
, format
);
228 vsnprintf(message2
, 65535, format
, ap
);
229 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
230 fprintf(log_stream
, "%s", message
);
234 vsnprintf(message2
, 65535, format
, ap
);
235 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
236 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
241 void _log_hex(int level
, const char *title
, const char *data
, int maxsize
)
244 const u8
*d
= (const u8
*)data
;
246 if (config
->debug
< level
) return;
248 // No support for _log_hex to syslog
251 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
252 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
254 for (i
= 0; i
< maxsize
; )
256 fprintf(log_stream
, "%4X: ", i
);
257 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
259 fprintf(log_stream
, "%02X ", d
[j
]);
261 fputs(": ", log_stream
);
264 for (; j
< i
+ 16; j
++)
266 fputs(" ", log_stream
);
268 fputs(": ", log_stream
);
271 fputs(" ", log_stream
);
272 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
274 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
275 fputc(d
[j
], log_stream
);
277 fputc('.', log_stream
);
280 fputs(" ", log_stream
);
284 fputs("\n", log_stream
);
288 setbuf(log_stream
, NULL
);
295 // This adds it to the routing table, advertises it
296 // via BGP if enabled, and stuffs it into the
297 // 'sessionbyip' cache.
299 // 'ip' and 'mask' must be in _host_ order.
301 static void routeset(sessionidt s
, ipt ip
, ipt mask
, ipt gw
, u8 add
)
306 if (!mask
) mask
= 0xffffffff;
308 ip
&= mask
; // Force the ip to be the first one in the route.
310 memset(&r
, 0, sizeof(r
));
311 r
.rt_dev
= config
->tundevice
;
312 r
.rt_dst
.sa_family
= AF_INET
;
313 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
314 r
.rt_gateway
.sa_family
= AF_INET
;
315 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
316 r
.rt_genmask
.sa_family
= AF_INET
;
317 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
318 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
320 r
.rt_flags
|= RTF_GATEWAY
;
321 else if (mask
== 0xffffffff)
322 r
.rt_flags
|= RTF_HOST
;
324 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
325 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
326 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
328 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
329 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
333 bgp_add_route(htonl(ip
), htonl(mask
));
335 bgp_del_route(htonl(ip
), htonl(mask
));
338 // Add/Remove the IPs to the 'sessionbyip' cache.
339 // Note that we add the zero address in the case of
340 // a network route. Roll on CIDR.
342 // Note that 's == 0' implies this is the address pool.
343 // We still cache it here, because it will pre-fill
344 // the malloc'ed tree.
348 if (!add
) // Are we deleting a route?
349 s
= 0; // Caching the session as '0' is the same as uncaching.
351 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
357 // Set up TUN interface
358 static void inittun(void)
361 struct sockaddr_in sin
= {0};
362 memset(&ifr
, 0, sizeof(ifr
));
363 ifr
.ifr_flags
= IFF_TUN
;
365 tunfd
= open(TUNDEVICE
, O_RDWR
);
368 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
372 int flags
= fcntl(tunfd
, F_GETFL
, 0);
373 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
375 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
377 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
380 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
381 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
382 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
384 sin
.sin_family
= AF_INET
;
385 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
386 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
388 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
390 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
393 /* Bump up the qlen to deal with bursts from the network */
395 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
397 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
400 ifr
.ifr_flags
= IFF_UP
;
401 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
403 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
409 static void initudp(void)
412 struct sockaddr_in addr
;
415 memset(&addr
, 0, sizeof(addr
));
416 addr
.sin_family
= AF_INET
;
417 addr
.sin_port
= htons(L2TPPORT
);
418 addr
.sin_addr
.s_addr
= config
->bind_address
;
419 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
420 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
422 int flags
= fcntl(udpfd
, F_GETFL
, 0);
423 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
425 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
427 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
430 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
433 memset(&addr
, 0, sizeof(addr
));
434 addr
.sin_family
= AF_INET
;
435 addr
.sin_port
= htons(NSCTL_PORT
);
436 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
437 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
438 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
440 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
446 // Find session by IP, < 1 for not found
448 // Confusingly enough, this 'ip' must be
449 // in _network_ order. This being the common
450 // case when looking it up from IP packet headers.
452 // We actually use this cache for two things.
453 // #1. For used IP addresses, this maps to the
454 // session ID that it's used by.
455 // #2. For un-used IP addresses, this maps to the
456 // index into the pool table that contains that
460 static int lookup_ipmap(ipt ip
)
463 char **d
= (char **) ip_hash
;
466 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
467 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
468 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
470 s
= (ipt
) d
[(size_t) *a
];
474 sessionidt
sessionbyip(ipt ip
)
476 int s
= lookup_ipmap(ip
);
477 CSTAT(call_sessionbyip
);
479 if (s
> 0 && s
< MAXSESSION
&& session
[s
].tunnel
)
485 // Take an IP address in HOST byte order and
486 // add it to the sessionid by IP cache.
488 // (It's actually cached in network order)
490 static void cache_ipmap(ipt ip
, int s
)
492 ipt nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char*)(&ip))[0]
494 char **d
= (char **) ip_hash
;
497 for (i
= 0; i
< 3; i
++)
499 if (!d
[(size_t) a
[i
]])
501 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof (void *))))
505 d
= (char **) d
[(size_t) a
[i
]];
508 d
[(size_t) a
[3]] = (char *)((int)s
);
511 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
514 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
515 // else a map to an ip pool index.
518 static void uncache_ipmap(ipt ip
)
520 cache_ipmap(ip
, 0); // Assign it to the NULL session.
524 // CLI list to dump current ipcache.
526 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
528 char **d
= (char **) ip_hash
, **e
, **f
, **g
;
532 if (CLI_HELP_REQUESTED
)
533 return CLI_HELP_NO_ARGS
;
535 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
537 for (i
= 0; i
< 256; ++i
)
542 for (j
= 0; j
< 256; ++j
)
547 for (k
= 0; k
< 256; ++k
)
552 for (l
= 0; l
< 256; ++l
)
556 cli_print(cli
, "%7d %d.%d.%d.%d", (int) g
[l
], i
, j
, k
, l
);
562 cli_print(cli
, "%d entries in cache", count
);
567 // Find session by username, 0 for not found
568 // walled garden users aren't authenticated, so the username is
569 // reasonably useless. Ignore them to avoid incorrect actions
571 // This is VERY inefficent. Don't call it often. :)
573 sessionidt
sessionbyuser(char *username
)
576 CSTAT(call_sessionbyuser
);
578 for (s
= 1; s
< MAXSESSION
; ++s
)
580 if (session
[s
].walled_garden
)
581 continue; // Skip walled garden users.
583 if (!strncmp(session
[s
].user
, username
, 128))
587 return 0; // Not found.
590 void send_garp(ipt ip
)
596 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
599 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
602 memset(&ifr
, 0, sizeof(ifr
));
603 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
604 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
606 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
610 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
611 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
613 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
618 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
621 // Find session by username, 0 for not found
622 static sessiont
*sessiontbysessionidt(sessionidt s
)
624 if (!s
|| s
> MAXSESSION
) return NULL
;
628 static sessionidt
sessionidtbysessiont(sessiont
*s
)
630 sessionidt val
= s
-session
;
631 if (s
< session
|| val
> MAXSESSION
) return 0;
635 // actually send a control message for a specific tunnel
636 void tunnelsend(u8
* buf
, u16 l
, tunnelidt t
)
638 struct sockaddr_in addr
;
640 CSTAT(call_tunnelsend
);
644 static int backtrace_count
= 0;
645 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
646 STAT(tunnel_tx_errors
);
647 log_backtrace(backtrace_count
, 5)
653 static int backtrace_count
= 0;
654 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
655 log_backtrace(backtrace_count
, 5)
656 STAT(tunnel_tx_errors
);
660 memset(&addr
, 0, sizeof(addr
));
661 addr
.sin_family
= AF_INET
;
662 *(u32
*) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
663 addr
.sin_port
= htons(tunnel
[t
].port
);
665 // sequence expected, if sequence in message
666 if (*buf
& 0x08) *(u16
*) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
668 // If this is a control message, deal with retries
671 tunnel
[t
].last
= time_now
; // control message sent
672 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
673 if (tunnel
[t
].try > 1)
675 STAT(tunnel_retries
);
676 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
680 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
682 LOG(0, ntohs((*(u16
*) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
683 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
684 STAT(tunnel_tx_errors
);
688 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
689 STAT(tunnel_tx_packets
);
690 INC_STAT(tunnel_tx_bytes
, l
);
694 // Tiny helper function to write data to
697 int tun_write(u8
* data
, int size
)
699 return write(tunfd
, data
, size
);
702 // process outgoing (to tunnel) IP
704 static void processipout(u8
* buf
, int len
)
711 char * data
= buf
; // Keep a copy of the originals.
716 CSTAT(call_processipout
);
718 if (len
< MIN_IP_SIZE
)
720 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
721 STAT(tunnel_tx_errors
);
726 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
727 STAT(tunnel_tx_errors
);
731 // Skip the tun header
735 // Got an IP header now
736 if (*(u8
*)(buf
) >> 4 != 4)
738 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
742 ip
= *(u32
*)(buf
+ 16);
743 if (!(s
= sessionbyip(ip
)))
745 // Is this a packet for a session that doesn't exist?
746 static int rate
= 0; // Number of ICMP packets we've sent this second.
747 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
749 if (last
!= time_now
)
755 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
757 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(u32
*)(buf
+ 12), 0));
758 host_unreachable(*(u32
*)(buf
+ 12), *(u16
*)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
762 t
= session
[s
].tunnel
;
765 // run access-list if any
766 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
771 // Are we throttling this session?
772 if (config
->cluster_iam_master
)
773 tbf_queue_packet(sp
->tbf_out
, data
, size
);
775 master_throttle_packet(sp
->tbf_out
, data
, size
);
778 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
780 // We are walled-gardening this
781 master_garden_packet(s
, data
, size
);
785 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
787 // Add on L2TP header
789 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
791 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
794 // Snooping this session, send it to intercept box
795 if (sp
->snoop_ip
&& sp
->snoop_port
)
796 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
798 sp
->cout
+= len
; // byte count
799 sp
->total_cout
+= len
; // byte count
802 sess_count
[s
].cout
+= len
; // To send to master..
806 // Helper routine for the TBF filters.
807 // Used to send queued data in to the user!
809 static void send_ipout(sessionidt s
, u8
*buf
, int len
)
817 if (len
< 0 || len
> MAXETHER
)
819 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
823 // Skip the tun header
827 ip
= *(u32
*)(buf
+ 16);
832 t
= session
[s
].tunnel
;
835 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
837 // Add on L2TP header
839 u8
*p
= makeppp(b
, sizeof(b
), buf
, len
, t
, s
, PPPIP
);
841 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
844 // Snooping this session.
845 if (sp
->snoop_ip
&& sp
->snoop_port
)
846 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
848 sp
->cout
+= len
; // byte count
849 sp
->total_cout
+= len
; // byte count
852 sess_count
[s
].cout
+= len
; // To send to master..
855 // add an AVP (16 bit)
856 static void control16(controlt
* c
, u16 avp
, u16 val
, u8 m
)
858 u16 l
= (m
? 0x8008 : 0x0008);
859 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
860 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
861 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
862 *(u16
*) (c
->buf
+ c
->length
+ 6) = htons(val
);
866 // add an AVP (32 bit)
867 static void control32(controlt
* c
, u16 avp
, u32 val
, u8 m
)
869 u16 l
= (m
? 0x800A : 0x000A);
870 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
871 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
872 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
873 *(u32
*) (c
->buf
+ c
->length
+ 6) = htonl(val
);
877 // add an AVP (32 bit)
878 static void controls(controlt
* c
, u16 avp
, char *val
, u8 m
)
880 u16 l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
881 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
882 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
883 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
884 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
885 c
->length
+= 6 + strlen(val
);
889 static void controlb(controlt
* c
, u16 avp
, char *val
, unsigned int len
, u8 m
)
891 u16 l
= ((m
? 0x8000 : 0) + len
+ 6);
892 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
893 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
894 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
895 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
896 c
->length
+= 6 + len
;
899 // new control connection
900 static controlt
*controlnew(u16 mtype
)
904 c
= malloc(sizeof(controlt
));
908 controlfree
= c
->next
;
912 *(u16
*) (c
->buf
+ 0) = htons(0xC802); // flags/ver
914 control16(c
, 0, mtype
, 1);
918 // send zero block if nothing is waiting
920 static void controlnull(tunnelidt t
)
923 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
926 *(u16
*) (buf
+ 0) = htons(0xC802); // flags/ver
927 *(u16
*) (buf
+ 2) = htons(12); // length
928 *(u16
*) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
929 *(u16
*) (buf
+ 6) = htons(0); // session
930 *(u16
*) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
931 *(u16
*) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
932 tunnelsend(buf
, 12, t
);
935 // add a control message to a tunnel, and send if within window
936 static void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
938 *(u16
*) (c
->buf
+ 2) = htons(c
->length
); // length
939 *(u16
*) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
940 *(u16
*) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
941 *(u16
*) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
942 tunnel
[t
].ns
++; // advance sequence
943 // link in message in to queue
944 if (tunnel
[t
].controlc
)
945 tunnel
[t
].controle
->next
= c
;
947 tunnel
[t
].controls
= c
;
949 tunnel
[t
].controle
= c
;
950 tunnel
[t
].controlc
++;
952 // send now if space in window
953 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
955 tunnel
[t
].try = 0; // first send
956 tunnelsend(c
->buf
, c
->length
, t
);
961 // Throttle or Unthrottle a session
963 // Throttle the data from/to through a session to no more than
964 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
967 // If either value is -1, the current value is retained for that
970 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
972 if (!session
[s
].tunnel
)
973 return; // No-one home.
975 if (!*session
[s
].user
)
976 return; // User not logged in
980 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
981 if (session
[s
].tbf_in
)
982 free_tbf(session
[s
].tbf_in
);
985 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
987 session
[s
].tbf_in
= 0;
989 session
[s
].throttle_in
= rate_in
;
994 int bytes
= rate_out
* 1024 / 8;
995 if (session
[s
].tbf_out
)
996 free_tbf(session
[s
].tbf_out
);
999 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1001 session
[s
].tbf_out
= 0;
1003 session
[s
].throttle_out
= rate_out
;
1007 // add/remove filters from session (-1 = no change)
1008 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1010 if (!session
[s
].tunnel
)
1011 return; // No-one home.
1013 if (!*session
[s
].user
)
1014 return; // User not logged in
1017 if (filter_in
> MAXFILTER
) filter_in
= -1;
1018 if (filter_out
> MAXFILTER
) filter_out
= -1;
1019 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1020 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1024 if (session
[s
].filter_in
)
1025 ip_filters
[session
[s
].filter_in
- 1].used
--;
1028 ip_filters
[filter_in
- 1].used
++;
1030 session
[s
].filter_in
= filter_in
;
1033 if (filter_out
>= 0)
1035 if (session
[s
].filter_out
)
1036 ip_filters
[session
[s
].filter_out
- 1].used
--;
1039 ip_filters
[filter_out
- 1].used
++;
1041 session
[s
].filter_out
= filter_out
;
1045 // start tidy shutdown of session
1046 void sessionshutdown(sessionidt s
, char *reason
)
1048 int walled_garden
= session
[s
].walled_garden
;
1051 CSTAT(call_sessionshutdown
);
1053 if (!session
[s
].tunnel
)
1055 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on a session with no tunnel.\n");
1056 return; // not a live session
1059 if (!session
[s
].die
)
1061 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1062 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
1063 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1066 // RADIUS Stop message
1067 if (session
[s
].opened
&& !walled_garden
&& !session
[s
].die
)
1069 u16 r
= session
[s
].radius
;
1072 if (!(r
= radiusnew(s
)))
1074 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1075 STAT(radius_overflow
);
1080 for (n
= 0; n
< 15; n
++)
1081 radius
[r
].auth
[n
] = rand();
1084 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
1085 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
1089 { // IP allocated, clear and unroute
1092 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1094 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1095 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1098 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1099 session
[s
].route
[r
].ip
= 0;
1102 if (session
[s
].ip_pool_index
== -1) // static ip
1104 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1111 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1112 throttle_session(s
, 0, 0);
1115 controlt
*c
= controlnew(14); // sending CDN
1116 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1117 control16(c
, 14, s
, 1); // assigned session (our end)
1118 controladd(c
, session
[s
].tunnel
, s
); // send the message
1121 if (!session
[s
].die
)
1122 session
[s
].die
= now() + 150; // Clean up in 15 seconds
1124 // update filter refcounts
1125 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1126 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1128 cluster_send_session(s
);
1131 void sendipcp(tunnelidt t
, sessionidt s
)
1134 u16 r
= session
[s
].radius
;
1137 CSTAT(call_sendipcp
);
1142 if (radius
[r
].state
!= RADIUSIPCP
)
1144 radius
[r
].state
= RADIUSIPCP
;
1148 radius
[r
].retry
= backoff(radius
[r
].try++);
1149 if (radius
[r
].try > 10)
1151 radiusclear(r
, s
); // Clear radius session.
1152 sessionshutdown(s
, "No reply on IPCP");
1156 q
= makeppp(buf
,sizeof(buf
), 0, 0, t
, s
, PPPIPCP
);
1160 q
[1] = r
<< RADIUS_SHIFT
; // ID, dont care, we only send one type of request
1161 *(u16
*) (q
+ 2) = htons(10);
1164 *(u32
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1165 config
->bind_address
? config
->bind_address
:
1166 my_address
; // send my IP
1168 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1169 session
[s
].flags
&= ~SF_IPCP_ACKED
; // Clear flag.
1172 // kill a session now
1173 static void sessionkill(sessionidt s
, char *reason
)
1176 CSTAT(call_sessionkill
);
1178 session
[s
].die
= now();
1179 sessionshutdown(s
, reason
); // close radius/routes, etc.
1180 if (session
[s
].radius
)
1181 radiusclear(session
[s
].radius
, s
); // cant send clean accounting data, session is killed
1183 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1185 memset(&session
[s
], 0, sizeof(session
[s
]));
1186 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1187 session
[s
].next
= sessionfree
;
1189 cli_session_actions
[s
].action
= 0;
1190 cluster_send_session(s
);
1193 static void tunnelclear(tunnelidt t
)
1196 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1197 tunnel
[t
].state
= TUNNELFREE
;
1200 // kill a tunnel now
1201 static void tunnelkill(tunnelidt t
, char *reason
)
1206 CSTAT(call_tunnelkill
);
1208 tunnel
[t
].state
= TUNNELDIE
;
1210 // free control messages
1211 while ((c
= tunnel
[t
].controls
))
1213 controlt
* n
= c
->next
;
1214 tunnel
[t
].controls
= n
;
1215 tunnel
[t
].controlc
--;
1216 c
->next
= controlfree
;
1220 for (s
= 1; s
< MAXSESSION
; s
++)
1221 if (session
[s
].tunnel
== t
)
1222 sessionkill(s
, reason
);
1226 LOG(1, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
1227 cli_tunnel_actions
[s
].action
= 0;
1228 cluster_send_tunnel(t
);
1231 // shut down a tunnel cleanly
1232 static void tunnelshutdown(tunnelidt t
, char *reason
)
1236 CSTAT(call_tunnelshutdown
);
1238 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1240 // never set up, can immediately kill
1241 tunnelkill(t
, reason
);
1244 LOG(1, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
1247 for (s
= 1; s
< MAXSESSION
; s
++)
1248 if (session
[s
].tunnel
== t
)
1249 sessionshutdown(s
, reason
);
1251 tunnel
[t
].state
= TUNNELDIE
;
1252 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
1253 cluster_send_tunnel(t
);
1254 // TBA - should we wait for sessions to stop?
1256 controlt
*c
= controlnew(4); // sending StopCCN
1257 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message)
1258 control16(c
, 9, t
, 1); // assigned tunnel (our end)
1259 controladd(c
, t
, 0); // send the message
1263 // read and process packet on tunnel (UDP)
1264 void processudp(u8
* buf
, int len
, struct sockaddr_in
*addr
)
1266 char *chapresponse
= NULL
;
1267 u16 l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
1271 CSTAT(call_processudp
);
1275 LOG_HEX(5, "UDP Data", buf
, len
);
1276 STAT(tunnel_rx_packets
);
1277 INC_STAT(tunnel_rx_bytes
, len
);
1280 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
1281 STAT(tunnel_rx_errors
);
1284 if ((buf
[1] & 0x0F) != 2)
1286 LOG(1, 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
1287 STAT(tunnel_rx_errors
);
1292 l
= ntohs(*(u16
*) p
);
1295 t
= ntohs(*(u16
*) p
);
1297 s
= ntohs(*(u16
*) p
);
1299 if (s
>= MAXSESSION
)
1301 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
1302 STAT(tunnel_rx_errors
);
1307 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
1308 STAT(tunnel_rx_errors
);
1313 ns
= ntohs(*(u16
*) p
);
1315 nr
= ntohs(*(u16
*) p
);
1320 u16 o
= ntohs(*(u16
*) p
);
1325 LOG(1, s
, t
, "Bad length %d>%d\n", (p
- buf
), l
);
1326 STAT(tunnel_rx_errors
);
1332 u16 message
= 0xFFFF; // message type
1334 u8 mandatorymessage
= 0;
1335 u8 chap
= 0; // if CHAP being used
1336 u16 asession
= 0; // assigned session
1337 u32 amagic
= 0; // magic number
1338 u8 aflags
= 0; // flags from last LCF
1339 u16 version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1340 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1341 char called
[MAXTEL
] = ""; // called number
1342 char calling
[MAXTEL
] = ""; // calling number
1344 if (!config
->cluster_iam_master
)
1346 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1350 if ((*buf
& 0xCA) != 0xC8)
1352 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
1353 STAT(tunnel_rx_errors
);
1357 // check for duplicate tunnel open message
1363 // Is this a duplicate of the first packet? (SCCRQ)
1365 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
1367 if (tunnel
[i
].state
!= TUNNELOPENING
||
1368 tunnel
[i
].ip
!= ntohl(*(ipt
*) & addr
->sin_addr
) ||
1369 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
1372 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
1377 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1378 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1380 // if no tunnel specified, assign one
1383 if (!(t
= new_tunnel()))
1385 LOG(1, 0, 0, "No more tunnels\n");
1386 STAT(tunnel_overflow
);
1390 tunnel
[t
].ip
= ntohl(*(ipt
*) & addr
->sin_addr
);
1391 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1392 tunnel
[t
].window
= 4; // default window
1393 STAT(tunnel_created
);
1394 LOG(1, 0, t
, " New tunnel from %s:%u ID %d\n",
1395 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
1398 // If the 'ns' just received is not the 'nr' we're
1399 // expecting, just send an ack and drop it.
1401 // if 'ns' is less, then we got a retransmitted packet.
1402 // if 'ns' is greater than missed a packet. Either way
1403 // we should ignore it.
1404 if (ns
!= tunnel
[t
].nr
)
1406 // is this the sequence we were expecting?
1407 STAT(tunnel_rx_errors
);
1408 LOG(1, 0, t
, " Out of sequence tunnel %d, (%d is not the expected %d)\n",
1409 t
, ns
, tunnel
[t
].nr
);
1411 if (l
) // Is this not a ZLB?
1416 // This is used to time out old tunnels
1417 tunnel
[t
].lastrec
= time_now
;
1419 // check sequence of this message
1421 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1422 // some to clear maybe?
1423 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1425 controlt
*c
= tunnel
[t
].controls
;
1426 tunnel
[t
].controls
= c
->next
;
1427 tunnel
[t
].controlc
--;
1428 c
->next
= controlfree
;
1431 tunnel
[t
].try = 0; // we have progress
1434 // receiver advance (do here so quoted correctly in any sends below)
1435 if (l
) tunnel
[t
].nr
= (ns
+ 1);
1436 if (skip
< 0) skip
= 0;
1437 if (skip
< tunnel
[t
].controlc
)
1439 // some control packets can now be sent that were previous stuck out of window
1440 int tosend
= tunnel
[t
].window
- skip
;
1441 controlt
*c
= tunnel
[t
].controls
;
1449 tunnel
[t
].try = 0; // first send
1450 tunnelsend(c
->buf
, c
->length
, t
);
1455 if (!tunnel
[t
].controlc
)
1456 tunnel
[t
].retry
= 0; // caught up
1459 { // if not a null message
1461 while (l
&& !(fatal
& 0x80))
1463 u16 n
= (ntohs(*(u16
*) p
) & 0x3FF);
1470 LOG(1, s
, t
, "Invalid length in AVP\n");
1471 STAT(tunnel_rx_errors
);
1478 // handle hidden AVPs
1479 if (!*config
->l2tpsecret
)
1481 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1485 if (!session
[s
].random_vector_length
)
1487 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
1491 LOG(4, s
, t
, "Hidden AVP\n");
1493 n
= unhide_avp(b
, t
, s
, n
);
1502 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1509 LOG(2, s
, t
, "Unknown AVP vendor %d\n", ntohs(*(u16
*) (b
)));
1514 mtype
= ntohs(*(u16
*) (b
));
1518 LOG(4, s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1521 case 0: // message type
1522 message
= ntohs(*(u16
*) b
);
1523 LOG(4, s
, t
, " Message type = %d (%s)\n", *b
, l2tp_message_types
[message
]);
1524 mandatorymessage
= flags
;
1526 case 1: // result code
1528 u16 rescode
= ntohs(*(u16
*)(b
));
1529 const char* resdesc
= "(unknown)";
1532 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1533 resdesc
= stopccn_result_codes
[rescode
];
1535 else if (message
== 14)
1537 if (rescode
<= MAX_CDN_RESULT_CODE
)
1538 resdesc
= cdn_result_codes
[rescode
];
1541 LOG(4, s
, t
, " Result Code %d: %s\n", rescode
, resdesc
);
1544 u16 errcode
= ntohs(*(u16
*)(b
+ 2));
1545 const char* errdesc
= "(unknown)";
1546 if (errcode
<= MAX_ERROR_CODE
)
1547 errdesc
= error_codes
[errcode
];
1548 LOG(4, s
, t
, " Error Code %d: %s\n", errcode
, errdesc
);
1551 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
1556 case 2: // protocol version
1558 version
= ntohs(*(u16
*) (b
));
1559 LOG(4, s
, t
, " Protocol version = %d\n", version
);
1560 if (version
&& version
!= 0x0100)
1561 { // allow 0.0 and 1.0
1562 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
1568 case 3: // framing capabilities
1569 // LOG(4, s, t, "Framing capabilities\n");
1571 case 4: // bearer capabilities
1572 // LOG(4, s, t, "Bearer capabilities\n");
1574 case 5: // tie breaker
1575 // We never open tunnels, so we don't care about tie breakers
1576 // LOG(4, s, t, "Tie breaker\n");
1578 case 6: // firmware revision
1579 // LOG(4, s, t, "Firmware revision\n");
1581 case 7: // host name
1582 memset(tunnel
[t
].hostname
, 0, 128);
1583 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1584 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1585 // TBA - to send to RADIUS
1587 case 8: // vendor name
1588 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
1589 memcpy(tunnel
[t
].vendor
, b
, (n
>= sizeof(tunnel
[t
].vendor
) - 1) ? sizeof(tunnel
[t
].vendor
) - 1 : n
);
1590 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1592 case 9: // assigned tunnel
1593 tunnel
[t
].far
= ntohs(*(u16
*) (b
));
1594 LOG(4, s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1596 case 10: // rx window
1597 tunnel
[t
].window
= ntohs(*(u16
*) (b
));
1598 if (!tunnel
[t
].window
)
1599 tunnel
[t
].window
= 1; // window of 0 is silly
1600 LOG(4, s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1602 case 11: // Challenge
1604 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
1605 build_chap_response(b
, 2, n
, &chapresponse
);
1608 case 13: // Response
1609 // Why did they send a response? We never challenge.
1610 LOG(2, s
, t
, " received unexpected challenge response\n");
1613 case 14: // assigned session
1614 asession
= session
[s
].far
= ntohs(*(u16
*) (b
));
1615 LOG(4, s
, t
, " assigned session = %d\n", asession
);
1617 case 15: // call serial number
1618 LOG(4, s
, t
, " call serial number = %d\n", ntohl(*(u32
*)b
));
1620 case 18: // bearer type
1621 LOG(4, s
, t
, " bearer type = %d\n", ntohl(*(u32
*)b
));
1624 case 19: // framing type
1625 LOG(4, s
, t
, " framing type = %d\n", ntohl(*(u32
*)b
));
1628 case 21: // called number
1629 memset(called
, 0, MAXTEL
);
1630 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1631 LOG(4, s
, t
, " Called <%s>\n", called
);
1633 case 22: // calling number
1634 memset(calling
, 0, MAXTEL
);
1635 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1636 LOG(4, s
, t
, " Calling <%s>\n", calling
);
1640 case 24: // tx connect speed
1643 session
[s
].tx_connect_speed
= ntohl(*(u32
*)b
);
1647 // AS5300s send connect speed as a string
1649 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1650 session
[s
].tx_connect_speed
= atol(tmp
);
1652 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
1654 case 38: // rx connect speed
1657 session
[s
].rx_connect_speed
= ntohl(*(u32
*)b
);
1661 // AS5300s send connect speed as a string
1663 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1664 session
[s
].rx_connect_speed
= atol(tmp
);
1666 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
1668 case 25: // Physical Channel ID
1670 u32 tmp
= ntohl(*(u32
*)b
);
1671 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
1674 case 29: // Proxy Authentication Type
1676 u16 authtype
= ntohs(*(u16
*)b
);
1677 LOG(4, s
, t
, " Proxy Auth Type %d (%s)\n", authtype
, authtypes
[authtype
]);
1678 requestchap
= (authtype
== 2);
1681 case 30: // Proxy Authentication Name
1683 char authname
[64] = {0};
1684 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1685 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
1689 case 31: // Proxy Authentication Challenge
1691 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1692 LOG(4, s
, t
, " Proxy Auth Challenge\n");
1695 case 32: // Proxy Authentication ID
1697 u16 authid
= ntohs(*(u16
*)(b
));
1698 LOG(4, s
, t
, " Proxy Auth ID (%d)\n", authid
);
1699 if (session
[s
].radius
)
1700 radius
[session
[s
].radius
].id
= authid
;
1703 case 33: // Proxy Authentication Response
1705 char authresp
[64] = {0};
1706 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1707 LOG(4, s
, t
, " Proxy Auth Response\n");
1710 case 27: // last send lcp
1711 { // find magic number
1712 u8
*p
= b
, *e
= p
+ n
;
1713 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
1715 if (*p
== 5 && p
[1] == 6) // Magic-Number
1716 amagic
= ntohl(*(u32
*) (p
+ 2));
1717 else if (*p
== 3 && p
[1] == 5 && *(u16
*) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5) // Authentication-Protocol
1719 else if (*p
== 7) // Protocol-Field-Compression
1720 aflags
|= SESSIONPFC
;
1721 else if (*p
== 8) // Address-and-Control-Field-Compression
1722 aflags
|= SESSIONACFC
;
1727 case 28: // last recv lcp confreq
1729 case 26: // Initial Received LCP CONFREQ
1731 case 39: // seq required - we control it as an LNS anyway...
1733 case 36: // Random Vector
1734 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1735 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1736 memcpy(session
[s
].random_vector
, b
, n
);
1737 session
[s
].random_vector_length
= n
;
1740 LOG(2, s
, t
, " Unknown AVP type %d\n", mtype
);
1747 tunnelshutdown(t
, "Unknown Mandatory AVP");
1751 case 1: // SCCRQ - Start Control Connection Request
1753 controlt
*c
= controlnew(2); // sending SCCRP
1754 control16(c
, 2, version
, 1); // protocol version
1755 control32(c
, 3, 3, 1); // framing
1756 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1757 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1758 control16(c
, 9, t
, 1); // assigned tunnel
1759 controladd(c
, t
, s
); // send the resply
1761 tunnel
[t
].state
= TUNNELOPENING
;
1764 tunnel
[t
].state
= TUNNELOPEN
;
1767 tunnel
[t
].state
= TUNNELOPEN
;
1768 controlnull(t
); // ack
1771 controlnull(t
); // ack
1772 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1773 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1776 controlnull(t
); // simply ACK
1790 STAT(session_overflow
);
1791 tunnelshutdown(t
, "No free sessions");
1799 sessionfree
= session
[s
].next
;
1800 memset(&session
[s
], 0, sizeof(session
[s
]));
1802 if (s
> config
->cluster_highest_sessionid
)
1803 config
->cluster_highest_sessionid
= s
;
1805 // make a RADIUS session
1806 if (!(r
= radiusnew(s
)))
1808 LOG(1, s
, t
, "No free RADIUS sessions for ICRQ\n");
1809 sessionkill(s
, "no free RADIUS sesions");
1813 c
= controlnew(11); // sending ICRP
1814 session
[s
].id
= sessionid
++;
1815 session
[s
].opened
= time(NULL
);
1816 session
[s
].tunnel
= t
;
1817 session
[s
].far
= asession
;
1818 session
[s
].last_packet
= time_now
;
1819 LOG(3, s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1820 control16(c
, 14, s
, 1); // assigned session
1821 controladd(c
, t
, s
); // send the reply
1823 // Generate a random challenge
1825 for (n
= 0; n
< 15; n
++)
1826 radius
[r
].auth
[n
] = rand();
1828 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1829 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1830 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1831 STAT(session_created
);
1838 if (amagic
== 0) amagic
= time_now
;
1839 session
[s
].magic
= amagic
; // set magic number
1840 session
[s
].l2tp_flags
= aflags
; // set flags received
1841 LOG(3, s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1842 controlnull(t
); // ack
1843 // In CHAP state, request PAP instead
1848 controlnull(t
); // ack
1849 sessionshutdown(s
, "Closed (Received CDN)");
1852 LOG(1, s
, t
, "Missing message type\n");
1855 STAT(tunnel_rx_errors
);
1856 if (mandatorymessage
& 0x80)
1857 tunnelshutdown(t
, "Unknown message");
1859 LOG(1, s
, t
, "Unknown message type %d\n", message
);
1862 if (chapresponse
) free(chapresponse
);
1863 cluster_send_tunnel(t
);
1867 LOG(4, s
, t
, " Got a ZLB ack\n");
1874 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
1875 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1876 { // HDLC address header, discard
1882 LOG(1, s
, t
, "Short ppp length %d\n", l
);
1883 STAT(tunnel_rx_errors
);
1893 prot
= ntohs(*(u16
*) p
);
1898 if (s
&& !session
[s
].tunnel
) // Is something wrong??
1900 if (!config
->cluster_iam_master
)
1902 // Pass it off to the master to deal with..
1903 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1908 LOG(1, s
, t
, "UDP packet contains session %d but no session[%d].tunnel "
1909 "exists (LAC said tunnel = %d). Dropping packet.\n", s
, s
, t
);
1911 STAT(tunnel_rx_errors
);
1917 session
[s
].last_packet
= time_now
;
1918 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1919 processpap(t
, s
, p
, l
);
1921 else if (prot
== PPPCHAP
)
1923 session
[s
].last_packet
= time_now
;
1924 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1925 processchap(t
, s
, p
, l
);
1927 else if (prot
== PPPLCP
)
1929 session
[s
].last_packet
= time_now
;
1930 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1931 processlcp(t
, s
, p
, l
);
1933 else if (prot
== PPPIPCP
)
1935 session
[s
].last_packet
= time_now
;
1936 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1937 processipcp(t
, s
, p
, l
);
1939 else if (prot
== PPPCCP
)
1941 session
[s
].last_packet
= time_now
;
1942 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
1943 processccp(t
, s
, p
, l
);
1945 else if (prot
== PPPIP
)
1949 LOG(4, s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1950 return; // closing session, PPP not processed
1953 session
[s
].last_packet
= time_now
;
1954 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
1956 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
1960 processipin(t
, s
, p
, l
);
1964 STAT(tunnel_rx_errors
);
1965 LOG(1, s
, t
, "Unknown PPP protocol %04X\n", prot
);
1970 // read and process packet on tun
1971 static void processtun(u8
* buf
, int len
)
1973 LOG_HEX(5, "Receive TUN Data", buf
, len
);
1974 STAT(tun_rx_packets
);
1975 INC_STAT(tun_rx_bytes
, len
);
1977 CSTAT(call_processtun
);
1983 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
1984 STAT(tun_rx_errors
);
1988 if (*(u16
*) (buf
+ 2) == htons(PKTIP
)) // IP
1989 processipout(buf
, len
);
1994 // Maximum number of actions to complete.
1995 // This is to avoid sending out too many packets
1997 #define MAX_ACTIONS 500
1999 static int regular_cleanups(void)
2001 static sessionidt s
= 0; // Next session to check for actions on.
2005 static clockt next_acct
= 0;
2008 LOG(3, 0, 0, "Begin regular cleanup\n");
2010 for (r
= 1; r
< MAXRADIUS
; r
++)
2012 if (!radius
[r
].state
)
2014 if (radius
[r
].retry
)
2016 if (radius
[r
].retry
<= TIME
)
2019 radius
[r
].retry
= backoff(radius
[r
].try+1); // Is this really needed? --mo
2021 for (t
= 1; t
<= config
->cluster_highest_tunnelid
; t
++)
2023 // check for expired tunnels
2024 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
2026 STAT(tunnel_timeout
);
2027 tunnelkill(t
, "Expired");
2030 // check for message resend
2031 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
2033 // resend pending messages as timeout on reply
2034 if (tunnel
[t
].retry
<= TIME
)
2036 controlt
*c
= tunnel
[t
].controls
;
2037 u8 w
= tunnel
[t
].window
;
2038 tunnel
[t
].try++; // another try
2039 if (tunnel
[t
].try > 5)
2040 tunnelkill(t
, "Timeout on control message"); // game over
2044 tunnelsend(c
->buf
, c
->length
, t
);
2050 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< TIME
+ 600)
2052 controlt
*c
= controlnew(6); // sending HELLO
2053 controladd(c
, t
, 0); // send the message
2054 LOG(3, 0, t
, "Sending HELLO message\n");
2057 // Check for tunnel changes requested from the CLI
2058 if ((a
= cli_tunnel_actions
[t
].action
))
2060 cli_tunnel_actions
[t
].action
= 0;
2061 if (a
& CLI_TUN_KILL
)
2063 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
2064 tunnelshutdown(t
, "Requested by administrator");
2071 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
2074 if (s
> config
->cluster_highest_sessionid
)
2077 if (!session
[s
].tunnel
) // Session isn't in use
2080 if (!session
[s
].die
&& session
[s
].ip
&& !(session
[s
].flags
& SF_IPCP_ACKED
))
2082 // IPCP has not completed yet. Resend
2083 LOG(3, s
, session
[s
].tunnel
, "No ACK for initial IPCP ConfigReq... resending\n");
2084 sendipcp(session
[s
].tunnel
, s
);
2087 // check for expired sessions
2088 if (session
[s
].die
&& session
[s
].die
<= TIME
)
2090 sessionkill(s
, "Expired");
2091 if (++count
>= MAX_ACTIONS
) break;
2095 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2096 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
2098 sessionkill(s
, "No response to LCP ECHO requests");
2099 STAT(session_timeout
);
2100 if (++count
>= MAX_ACTIONS
) break;
2104 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2105 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
2107 u8 b
[MAXCONTROL
] = {0};
2109 u8
*q
= makeppp(b
, sizeof(b
), 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
2113 *(u8
*)(q
+ 1) = (time_now
% 255); // ID
2114 *(u16
*)(q
+ 2) = htons(8); // Length
2115 *(u32
*)(q
+ 4) = 0; // Magic Number (not supported)
2117 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
2118 (int)(time_now
- session
[s
].last_packet
));
2119 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
2120 if (++count
>= MAX_ACTIONS
) break;
2123 // Check for actions requested from the CLI
2124 if ((a
= cli_session_actions
[s
].action
))
2128 cli_session_actions
[s
].action
= 0;
2129 if (a
& CLI_SESS_KILL
)
2131 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
2132 sessionshutdown(s
, "Requested by administrator");
2133 a
= 0; // dead, no need to check for other actions
2136 if (a
& CLI_SESS_NOSNOOP
)
2138 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
2139 session
[s
].snoop_ip
= 0;
2140 session
[s
].snoop_port
= 0;
2143 else if (a
& CLI_SESS_SNOOP
)
2145 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%d)\n",
2146 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
2147 cli_session_actions
[s
].snoop_port
);
2149 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
2150 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
2154 if (a
& CLI_SESS_NOTHROTTLE
)
2156 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
2157 throttle_session(s
, 0, 0);
2160 else if (a
& CLI_SESS_THROTTLE
)
2162 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
2163 cli_session_actions
[s
].throttle_in
,
2164 cli_session_actions
[s
].throttle_out
);
2166 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
2170 if (a
& CLI_SESS_NOFILTER
)
2172 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
2173 filter_session(s
, 0, 0);
2176 else if (a
& CLI_SESS_FILTER
)
2178 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
2179 cli_session_actions
[s
].filter_in
,
2180 cli_session_actions
[s
].filter_out
);
2182 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
2187 cluster_send_session(s
);
2189 if (++count
>= MAX_ACTIONS
) break;
2193 if (*config
->accounting_dir
&& next_acct
<= TIME
)
2195 // Dump accounting data
2196 next_acct
= TIME
+ ACCT_TIME
;
2200 if (count
>= MAX_ACTIONS
)
2201 return 1; // Didn't finish!
2203 LOG(3, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count
, config
->cleanup_interval
);
2209 // Are we in the middle of a tunnel update, or radius
2212 static int still_busy(void)
2215 static clockt last_talked
= 0;
2216 static clockt start_busy_wait
= 0;
2217 if (start_busy_wait
== 0)
2218 start_busy_wait
= TIME
;
2220 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
2222 if (!tunnel
[i
].controlc
)
2225 if (last_talked
!= TIME
)
2227 LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i
);
2233 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2234 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
2236 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2240 for (i
= 1; i
< MAXRADIUS
; i
++)
2242 if (radius
[i
].state
== RADIUSNULL
)
2244 if (radius
[i
].state
== RADIUSWAIT
)
2247 if (last_talked
!= TIME
)
2249 LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i
, radius
[i
].session
);
2258 static fd_set readset
;
2259 static int readset_n
= 0;
2261 // main loop - gets packets on tun or udp and processes them
2262 static void mainloop(void)
2267 clockt next_cluster_ping
= 0; // send initial ping immediately
2268 time_t next_clean
= time_now
+ config
->cleanup_interval
;
2270 LOG(4, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2271 udpfd
, tunfd
, cluster_sockfd
, controlfd
);
2274 FD_SET(udpfd
, &readset
);
2275 FD_SET(tunfd
, &readset
);
2276 FD_SET(controlfd
, &readset
);
2277 FD_SET(clifd
, &readset
);
2278 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &readset
);
2280 if (tunfd
> readset_n
) readset_n
= tunfd
;
2281 if (controlfd
> readset_n
) readset_n
= controlfd
;
2282 if (clifd
> readset_n
) readset_n
= clifd
;
2283 if (cluster_sockfd
> readset_n
) readset_n
= cluster_sockfd
;
2285 while (!main_quit
|| still_busy())
2291 int bgp_set
[BGP_NUM_PEERS
];
2294 if (config
->reload_config
)
2296 // Update the config state based on config settings
2300 memcpy(&r
, &readset
, sizeof(fd_set
));
2302 to
.tv_usec
= 100000; // 1/10th of a second.
2306 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2308 bgp_set
[i
] = bgp_select_state(&bgp_peers
[i
]);
2311 FD_SET(bgp_peers
[i
].sock
, &r
);
2312 if (bgp_peers
[i
].sock
> n
)
2313 n
= bgp_peers
[i
].sock
;
2318 FD_SET(bgp_peers
[i
].sock
, &w
);
2319 if (bgp_peers
[i
].sock
> n
)
2320 n
= bgp_peers
[i
].sock
;
2324 n
= select(n
+ 1, &r
, &w
, 0, &to
);
2326 n
= select(n
+ 1, &r
, 0, 0, &to
);
2332 if (errno
== EINTR
||
2333 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
2336 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
2342 struct sockaddr_in addr
;
2346 if (FD_ISSET(controlfd
, &r
))
2348 alen
= sizeof(addr
);
2349 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
, alen
);
2354 if (config
->cluster_iam_master
)
2356 for (i
= 0; i
< config
->num_radfds
; i
++)
2358 if (FD_ISSET(radfds
[i
], &r
))
2360 processrad(buf
, recv(radfds
[i
], buf
, sizeof(buf
), 0), i
);
2367 if (FD_ISSET(clifd
, &r
))
2371 alen
= sizeof(addr
);
2372 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &len
)) >= 0)
2378 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
2384 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
2386 int isr
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &r
) : 0;
2387 int isw
= bgp_set
[i
] ? FD_ISSET(bgp_peers
[i
].sock
, &w
) : 0;
2388 bgp_process(&bgp_peers
[i
], isr
, isw
);
2394 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
2397 if (FD_ISSET(udpfd
, &r
))
2399 alen
= sizeof(addr
);
2400 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
2402 processudp(buf
, s
, &addr
);
2412 if (FD_ISSET(tunfd
, &r
))
2414 if ((n
= read(tunfd
, buf
, sizeof(buf
))) > 0)
2426 if (FD_ISSET(cluster_sockfd
, &r
))
2428 alen
= sizeof(addr
);
2429 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
2431 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
2435 FD_CLR(cluster_sockfd
, &r
);
2442 // Runs on every machine (master and slaves).
2443 if (cluster_sockfd
&& next_cluster_ping
<= TIME
)
2445 // Check to see which of the cluster is still alive..
2447 cluster_send_ping(basetime
); // Only does anything if we're a slave
2448 cluster_check_master(); // ditto.
2450 cluster_heartbeat(); // Only does anything if we're a master.
2451 cluster_check_slaves(); // ditto.
2453 master_update_counts(); // If we're a slave, send our byte counters to our master.
2455 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
2456 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
2458 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
2461 // Run token bucket filtering queue..
2462 // Only run it every 1/10th of a second.
2463 // Runs on all machines both master and slave.
2465 static clockt last_run
= 0;
2466 if (last_run
!= TIME
)
2473 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2474 * something to read, else under load this will never actually run....
2477 if (config
->cluster_iam_master
&& next_clean
<= time_now
)
2479 if (regular_cleanups())
2482 next_clean
= time_now
+ 1 ; // Didn't finish. Check quickly.
2486 next_clean
= time_now
+ config
->cleanup_interval
; // Did. Move to next interval.
2491 // Are we the master and shutting down??
2492 if (config
->cluster_iam_master
)
2493 cluster_heartbeat(); // Flush any queued changes..
2495 // Ok. Notify everyone we're shutting down. If we're
2496 // the master, this will force an election.
2497 cluster_send_ping(0);
2500 // Important!!! We MUST not process any packets past this point!
2503 static void stripdomain(char *host
)
2507 if ((p
= strchr(host
, '.')))
2513 FILE *resolv
= fopen("/etc/resolv.conf", "r");
2519 while (fgets(buf
, sizeof(buf
), resolv
))
2521 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
2524 if (!isspace(buf
[6]))
2528 while (isspace(*b
)) b
++;
2533 while (*b
&& !isspace(*b
)) b
++;
2535 if (buf
[0] == 'd') // domain is canonical
2541 // first search line
2544 // hold, may be subsequent domain line
2545 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
2556 int hl
= strlen(host
);
2557 int dl
= strlen(domain
);
2558 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
2559 host
[hl
-dl
- 1] = 0;
2563 *p
= 0; // everything after first dot
2568 // Init data structures
2569 static void initdata(int optdebug
, char *optconfig
)
2573 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
2575 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
2578 if (!(config
= shared_malloc(sizeof(configt
))))
2580 LOG(0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno
));
2583 memset(config
, 0, sizeof(configt
));
2584 time(&config
->start_time
);
2585 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
2586 config
->debug
= optdebug
;
2587 config
->num_tbfs
= MAXTBFS
;
2588 config
->rl_rate
= 28; // 28kbps
2590 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
2592 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
2595 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
2597 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
2601 if (!(sess_count
= shared_malloc(sizeof(sessioncountt
) * MAXSESSION
)))
2603 LOG(0, 0, 0, "Error doing malloc for sessions_count: %s\n", strerror(errno
));
2607 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
2609 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
2613 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
2615 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
2619 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
2621 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
2624 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
2627 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
2629 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
2632 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
2635 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
2637 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
2640 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
2642 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
2644 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
2647 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
2649 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
2650 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
2651 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
2652 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
2654 // Put all the sessions on the free list marked as undefined.
2655 for (i
= 1; i
< MAXSESSION
- 1; i
++)
2657 session
[i
].next
= i
+ 1;
2658 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
2660 session
[MAXSESSION
- 1].next
= 0;
2663 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2664 for (i
= 1; i
< MAXTUNNEL
- 1; i
++)
2665 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
2669 // Grab my hostname unless it's been specified
2670 gethostname(hostname
, sizeof(hostname
));
2671 stripdomain(hostname
);
2674 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
2677 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
2679 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
2685 static int assign_ip_address(sessionidt s
)
2689 time_t best_time
= time_now
;
2690 char *u
= session
[s
].user
;
2694 CSTAT(call_assign_ip_address
);
2696 for (i
= 1; i
< ip_pool_size
; i
++)
2698 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
2701 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
2708 if (ip_address_pool
[i
].last
< best_time
)
2711 if (!(best_time
= ip_address_pool
[i
].last
))
2712 break; // never used, grab this one
2718 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
2722 session
[s
].ip
= ip_address_pool
[best
].address
;
2723 session
[s
].ip_pool_index
= best
;
2724 ip_address_pool
[best
].assigned
= 1;
2725 ip_address_pool
[best
].last
= time_now
;
2726 ip_address_pool
[best
].session
= s
;
2727 if (session
[s
].walled_garden
)
2728 /* Don't track addresses of users in walled garden (note: this
2729 means that their address isn't "sticky" even if they get
2731 ip_address_pool
[best
].user
[0] = 0;
2733 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2736 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
2737 reuse
? "Reusing" : "Allocating", best
);
2742 static void free_ip_address(sessionidt s
)
2744 int i
= session
[s
].ip_pool_index
;
2747 CSTAT(call_free_ip_address
);
2750 return; // what the?
2752 if (i
< 0) // Is this actually part of the ip pool?
2756 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
2758 ip_address_pool
[i
].assigned
= 0;
2759 ip_address_pool
[i
].session
= 0;
2760 ip_address_pool
[i
].last
= time_now
;
2764 // Fsck the address pool against the session table.
2765 // Normally only called when we become a master.
2767 // This isn't perfect: We aren't keep tracking of which
2768 // users used to have an IP address.
2770 void rebuild_address_pool(void)
2775 // Zero the IP pool allocation, and build
2776 // a map from IP address to pool index.
2777 for (i
= 1; i
< MAXIPPOOL
; ++i
)
2779 ip_address_pool
[i
].assigned
= 0;
2780 ip_address_pool
[i
].session
= 0;
2781 if (!ip_address_pool
[i
].address
)
2784 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
2787 for (i
= 0; i
< MAXSESSION
; ++i
)
2790 if (!session
[i
].ip
|| !session
[i
].tunnel
)
2792 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
2794 if (session
[i
].ip_pool_index
< 0)
2796 // Not allocated out of the pool.
2797 if (ipid
< 1) // Not found in the pool either? good.
2800 LOG(0, i
, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2801 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
2803 // Fall through and process it as part of the pool.
2807 if (ipid
> MAXIPPOOL
|| ipid
< 0)
2809 LOG(0, i
, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
2811 session
[i
].ip_pool_index
= ipid
;
2815 ip_address_pool
[ipid
].assigned
= 1;
2816 ip_address_pool
[ipid
].session
= i
;
2817 ip_address_pool
[ipid
].last
= time_now
;
2818 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2819 session
[i
].ip_pool_index
= ipid
;
2820 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
2825 // Fix the address pool to match a changed session.
2826 // (usually when the master sends us an update).
2827 static void fix_address_pool(int sid
)
2831 ipid
= session
[sid
].ip_pool_index
;
2833 if (ipid
> ip_pool_size
)
2834 return; // Ignore it. rebuild_address_pool will fix it up.
2836 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
2837 return; // Just ignore it. rebuild_address_pool will take care of it.
2839 ip_address_pool
[ipid
].assigned
= 1;
2840 ip_address_pool
[ipid
].session
= sid
;
2841 ip_address_pool
[ipid
].last
= time_now
;
2842 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
2846 // Add a block of addresses to the IP pool to hand out.
2848 static void add_to_ip_pool(u32 addr
, u32 mask
)
2852 mask
= 0xffffffff; // Host route only.
2856 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
2859 for (i
= addr
;(i
& mask
) == addr
; ++i
)
2861 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
2862 continue; // Skip 0 and broadcast addresses.
2864 ip_address_pool
[ip_pool_size
].address
= i
;
2865 ip_address_pool
[ip_pool_size
].assigned
= 0;
2867 if (ip_pool_size
>= MAXIPPOOL
)
2869 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
2875 // Initialize the IP address pool
2876 static void initippool()
2881 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2883 if (!(f
= fopen(IPPOOLFILE
, "r")))
2885 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2889 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2892 buf
[4095] = 0; // Force it to be zero terminated/
2894 if (*buf
== '#' || *buf
== '\n')
2895 continue; // Skip comments / blank lines
2896 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2897 if ((p
= (char *)strchr(buf
, ':')))
2901 src
= inet_addr(buf
);
2902 if (src
== INADDR_NONE
)
2904 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
2907 // This entry is for a specific IP only
2908 if (src
!= config
->bind_address
)
2913 if ((p
= (char *)strchr(pool
, '/')))
2917 u32 start
= 0, mask
= 0;
2919 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
2921 if (!*p
|| !(numbits
= atoi(p
)))
2923 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
2926 start
= ntohl(inet_addr(pool
));
2927 mask
= (u32
)(pow(2, numbits
) - 1) << (32 - numbits
);
2929 // Add a static route for this pool
2930 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
2931 fmtaddr(htonl(start
), 0), 32 + mask
);
2933 routeset(0, start
, mask
, 0, 1);
2935 add_to_ip_pool(start
, mask
);
2939 // It's a single ip address
2940 add_to_ip_pool(inet_addr(pool
), 0);
2944 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
2947 void snoop_send_packet(char *packet
, u16 size
, ipt destination
, u16 port
)
2949 struct sockaddr_in snoop_addr
= {0};
2950 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2953 snoop_addr
.sin_family
= AF_INET
;
2954 snoop_addr
.sin_addr
.s_addr
= destination
;
2955 snoop_addr
.sin_port
= ntohs(port
);
2957 LOG(5, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n",
2958 packet
, size
, fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
2959 htons(snoop_addr
.sin_port
));
2961 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
2962 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
2964 STAT(packets_snooped
);
2967 static void dump_acct_info()
2969 char filename
[1024];
2971 time_t t
= time(NULL
);
2976 CSTAT(call_dump_acct_info
);
2978 strftime(timestr
, 64, "%Y%m%d%H%M%S", localtime(&t
));
2979 snprintf(filename
, 1024, "%s/%s", config
->accounting_dir
, timestr
);
2981 for (i
= 0; i
< MAXSESSION
; i
++)
2983 if (!session
[i
].opened
|| !session
[i
].ip
|| !(session
[i
].cin
|| session
[i
].cout
) || !*session
[i
].user
|| session
[i
].walled_garden
)
2987 time_t now
= time(NULL
);
2988 if (!(f
= fopen(filename
, "w")))
2990 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
2993 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
2994 fprintf(f
, "# dslwatch.pl dump file V1.01\n"
2998 "# format: username ip qos uptxoctets downrxoctets\n",
3004 LOG(4, 0, 0, "Dumping accounting information for %s\n", session
[i
].user
);
3005 fprintf(f
, "%s %s %d %u %u\n",
3006 session
[i
].user
, // username
3007 fmtaddr(htonl(session
[i
].ip
), 0), // ip
3008 (session
[i
].throttle_in
|| session
[i
].throttle_out
) ? 2 : 1, // qos
3009 (u32
)session
[i
].cin
, // uptxoctets
3010 (u32
)session
[i
].cout
); // downrxoctets
3012 session
[i
].pin
= session
[i
].cin
= 0;
3013 session
[i
].pout
= session
[i
].cout
= 0;
3021 int main(int argc
, char *argv
[])
3025 char *optconfig
= CONFIGFILE
;
3027 time(&basetime
); // start clock
3030 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
3035 if (fork()) exit(0);
3037 freopen("/dev/null", "r", stdin
);
3038 freopen("/dev/null", "w", stdout
);
3039 freopen("/dev/null", "w", stderr
);
3048 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
3051 printf("Args are:\n"
3052 "\t-d\t\tDetach from terminal\n"
3053 "\t-c <file>\tConfig file\n"
3054 "\t-h <hostname>\tForce hostname\n"
3062 // Start the timer routine off
3064 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3065 signal(SIGALRM
, sigalrm_handler
);
3066 siginterrupt(SIGALRM
, 0);
3069 initdata(optdebug
, optconfig
);
3073 init_tbf(config
->num_tbfs
);
3075 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
3076 LOG(0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
3077 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3080 rlim
.rlim_cur
= RLIM_INFINITY
;
3081 rlim
.rlim_max
= RLIM_INFINITY
;
3082 // Remove the maximum core size
3083 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
3084 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
3086 // Make core dumps go to /tmp
3090 if (config
->scheduler_fifo
)
3093 struct sched_param params
= {0};
3094 params
.sched_priority
= 1;
3096 if (get_nprocs() < 2)
3098 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3099 config
->scheduler_fifo
= 0;
3103 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
3105 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3109 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
3110 config
->scheduler_fifo
= 0;
3115 /* Set up the cluster communications port. */
3116 if (cluster_init() < 0)
3120 signal(SIGPIPE
, SIG_IGN
);
3121 bgp_setup(config
->as_number
);
3122 bgp_add_route(config
->bind_address
, 0xffffffff);
3123 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3125 if (config
->neighbour
[i
].name
[0])
3126 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3127 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3128 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3133 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
3141 signal(SIGHUP
, sighup_handler
);
3142 signal(SIGTERM
, sigterm_handler
);
3143 signal(SIGINT
, sigterm_handler
);
3144 signal(SIGQUIT
, sigquit_handler
);
3145 signal(SIGCHLD
, sigchild_handler
);
3147 // Prevent us from getting paged out
3148 if (config
->lock_pages
)
3150 if (!mlockall(MCL_CURRENT
))
3151 LOG(1, 0, 0, "Locking pages into memory\n");
3153 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
3158 // Drop privileges here
3159 if (config
->target_uid
> 0 && geteuid() == 0)
3160 setuid(config
->target_uid
);
3165 /* try to shut BGP down cleanly; with luck the sockets will be
3166 writable since we're out of the select */
3167 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3168 if (bgp_peers
[i
].state
== Established
)
3169 bgp_stop(&bgp_peers
[i
]);
3172 /* remove plugins (so cleanup code gets run) */
3175 // Remove the PID file if we wrote it
3176 if (config
->wrote_pid
&& *config
->pid_file
== '/')
3177 unlink(config
->pid_file
);
3179 /* kill CLI children */
3180 signal(SIGTERM
, SIG_IGN
);
3185 static void sighup_handler(int sig
)
3187 if (log_stream
&& log_stream
!= stderr
)
3196 static void sigalrm_handler(int sig
)
3198 // Log current traffic stats
3200 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3201 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3202 (udp_rx
/ 1024.0 / 1024.0 * 8),
3203 (eth_tx
/ 1024.0 / 1024.0 * 8),
3204 (eth_rx
/ 1024.0 / 1024.0 * 8),
3205 (udp_tx
/ 1024.0 / 1024.0 * 8),
3206 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
3207 udp_rx_pkt
, eth_rx_pkt
);
3209 udp_tx
= udp_rx
= 0;
3210 udp_rx_pkt
= eth_rx_pkt
= 0;
3211 eth_tx
= eth_rx
= 0;
3213 if (config
->dump_speed
)
3214 printf("%s\n", config
->bandwidth
);
3216 // Update the internal time counter
3218 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3223 struct param_timer p
= { time_now
};
3224 run_plugins(PLUGIN_TIMER
, &p
);
3229 static void sigterm_handler(int sig
)
3231 LOG(1, 0, 0, "Shutting down cleanly\n");
3232 if (config
->save_state
)
3238 static void sigquit_handler(int sig
)
3242 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3243 for (i
= 1; i
< MAXSESSION
; i
++)
3245 if (session
[i
].opened
)
3246 sessionkill(i
, "L2TPNS Closing");
3248 for (i
= 1; i
< MAXTUNNEL
; i
++)
3250 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3251 tunnelshutdown(i
, "L2TPNS Closing");
3257 static void sigchild_handler(int sig
)
3259 while (waitpid(-1, NULL
, WNOHANG
) > 0)
3263 static void read_state()
3269 char magic
[sizeof(DUMP_MAGIC
) - 1];
3272 if (!config
->save_state
)
3278 if (stat(STATEFILE
, &sb
) < 0)
3284 if (sb
.st_mtime
< (time(NULL
) - 60))
3286 LOG(0, 0, 0, "State file is too old to read, ignoring\n");
3291 f
= fopen(STATEFILE
, "r");
3296 LOG(0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
3300 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
3302 LOG(0, 0, 0, "Bad state file magic\n");
3306 LOG(1, 0, 0, "Reading state information\n");
3307 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
3309 LOG(0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3313 if (buf
[0] > ip_pool_size
)
3315 LOG(0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
3319 LOG(2, 0, 0, "Loading %u ip addresses\n", buf
[0]);
3320 for (i
= 0; i
< buf
[0]; i
++)
3322 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
3324 LOG(0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
3328 if (itmp
.address
!= ip_address_pool
[i
].address
)
3330 LOG(0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
3334 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
3337 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
3339 LOG(0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3343 LOG(2, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
3344 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3346 LOG(0, 0, 0, "Error reading tunnel data from state file\n");
3350 for (i
= 0; i
< MAXTUNNEL
; i
++)
3352 tunnel
[i
].controlc
= 0;
3353 tunnel
[i
].controls
= NULL
;
3354 tunnel
[i
].controle
= NULL
;
3355 if (*tunnel
[i
].hostname
)
3356 LOG(3, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
3359 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
3361 LOG(0, 0, 0, "Error/mismatch reading session header from state file\n");
3365 LOG(2, 0, 0, "Loading %u sessions\n", MAXSESSION
);
3366 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3368 LOG(0, 0, 0, "Error reading session data from state file\n");
3372 for (i
= 0; i
< MAXSESSION
; i
++)
3374 session
[i
].tbf_in
= 0;
3375 session
[i
].tbf_out
= 0;
3376 if (session
[i
].opened
)
3378 LOG(2, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
3380 sessionsetup(session
[i
].tunnel
, i
);
3385 LOG(0, 0, 0, "Loaded saved state information\n");
3388 static void dump_state()
3393 if (!config
->save_state
)
3398 if (!(f
= fopen(STATEFILE
, "w")))
3401 LOG(1, 0, 0, "Dumping state information\n");
3403 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
) - 1, 1, f
) != 1)
3406 LOG(2, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
3407 buf
[0] = ip_pool_size
;
3408 buf
[1] = sizeof(ippoolt
);
3409 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3411 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
)
3414 LOG(2, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
3416 buf
[1] = sizeof(tunnelt
);
3417 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3419 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
3422 LOG(2, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
3423 buf
[0] = MAXSESSION
;
3424 buf
[1] = sizeof(sessiont
);
3425 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1)
3427 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
3435 LOG(0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
3439 static void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
)
3442 *challenge_response
= NULL
;
3444 if (!*config
->l2tpsecret
)
3446 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3450 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
3452 *challenge_response
= (char *)calloc(17, 1);
3455 MD5Update(&ctx
, &id
, 1);
3456 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
3457 MD5Update(&ctx
, challenge
, challenge_length
);
3458 MD5Final(*challenge_response
, &ctx
);
3463 static int facility_value(char *name
)
3466 for (i
= 0; facilitynames
[i
].c_name
; i
++)
3468 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
3469 return facilitynames
[i
].c_val
;
3474 static void update_config()
3477 static int timeout
= 0;
3478 static int interval
= 0;
3488 if (*config
->log_filename
)
3490 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
3492 char *p
= config
->log_filename
+ 7;
3495 openlog("l2tpns", LOG_PID
, facility_value(p
));
3499 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
3501 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
3503 fseek(log_stream
, 0, SEEK_END
);
3504 setbuf(log_stream
, NULL
);
3508 log_stream
= stderr
;
3509 setbuf(log_stream
, NULL
);
3515 log_stream
= stderr
;
3516 setbuf(log_stream
, NULL
);
3521 config
->numradiusservers
= 0;
3522 for (i
= 0; i
< MAXRADSERVER
; i
++)
3523 if (config
->radiusserver
[i
])
3525 config
->numradiusservers
++;
3526 // Set radius port: if not set, take the port from the
3527 // first radius server. For the first radius server,
3528 // take the #defined default value from l2tpns.h
3530 // test twice, In case someone works with
3531 // a secondary radius server without defining
3532 // a primary one, this will work even then.
3533 if (i
>0 && !config
->radiusport
[i
])
3534 config
->radiusport
[i
] = config
->radiusport
[i
-1];
3535 if (!config
->radiusport
[i
])
3536 config
->radiusport
[i
] = RADPORT
;
3539 if (!config
->numradiusservers
)
3540 LOG(0, 0, 0, "No RADIUS servers defined!\n");
3542 config
->num_radfds
= 2 << RADIUS_SHIFT
;
3545 for (i
= 0; i
< MAXPLUGINS
; i
++)
3547 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
3550 if (*config
->plugins
[i
])
3553 add_plugin(config
->plugins
[i
]);
3555 else if (*config
->old_plugins
[i
])
3558 remove_plugin(config
->old_plugins
[i
]);
3561 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
3562 if (!config
->cleanup_interval
) config
->cleanup_interval
= 10;
3563 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
3564 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
3565 if (!*config
->cluster_interface
)
3566 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
3568 if (!config
->cluster_hb_interval
)
3569 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
3571 if (!config
->cluster_hb_timeout
)
3572 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
3574 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
3576 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3577 // late, ensure we're sufficiently larger than that
3578 int t
= 4 * config
->cluster_hb_interval
+ 11;
3580 if (config
->cluster_hb_timeout
< t
)
3582 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
3583 config
->cluster_hb_timeout
= t
;
3586 // Push timing changes to the slaves immediately if we're the master
3587 if (config
->cluster_iam_master
)
3588 cluster_heartbeat();
3590 interval
= config
->cluster_hb_interval
;
3591 timeout
= config
->cluster_hb_timeout
;
3595 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
3598 if ((f
= fopen(config
->pid_file
, "w")))
3600 fprintf(f
, "%d\n", getpid());
3602 config
->wrote_pid
= 1;
3606 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
3610 config
->reload_config
= 0;
3613 static void read_config_file()
3617 if (!config
->config_file
) return;
3618 if (!(f
= fopen(config
->config_file
, "r")))
3620 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
3624 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
3626 LOG(3, 0, 0, "Done reading config file\n");
3631 int sessionsetup(tunnelidt t
, sessionidt s
)
3633 // A session now exists, set it up
3639 CSTAT(call_sessionsetup
);
3641 LOG(3, s
, t
, "Doing session setup for session\n");
3643 if (!session
[s
].ip
|| session
[s
].ip
== 0xFFFFFFFE)
3645 assign_ip_address(s
);
3648 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
3649 sessionshutdown(s
, "No IP addresses available");
3652 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
3653 fmtaddr(htonl(session
[s
].ip
), 0));
3657 // Make sure this is right
3658 session
[s
].tunnel
= t
;
3660 // zap old sessions with same IP and/or username
3661 // Don't kill gardened sessions - doing so leads to a DoS
3662 // from someone who doesn't need to know the password
3665 user
= session
[s
].user
;
3666 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
3668 if (i
== s
) continue;
3669 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
3670 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
3671 sessionkill(i
, "Duplicate session for users");
3678 // Add the route for this session.
3679 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
3681 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
3682 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
3685 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
3688 // Static IPs need to be routed if not already
3689 // convered by a Framed-Route. Anything else is part
3690 // of the IP address pool and is already routed, it
3691 // just needs to be added to the IP cache.
3692 if (session
[s
].ip_pool_index
== -1) // static ip
3694 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
3697 cache_ipmap(session
[s
].ip
, s
);
3700 if (!session
[s
].unique_id
)
3702 // did this session just finish radius?
3703 LOG(3, s
, t
, "Sending initial IPCP to client\n");
3705 session
[s
].unique_id
= ++last_id
;
3708 // Run the plugin's against this new session.
3710 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
3711 run_plugins(PLUGIN_NEW_SESSION
, &data
);
3714 // Allocate TBFs if throttled
3715 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
3716 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
3718 session
[s
].last_packet
= time_now
;
3720 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
3721 fmtaddr(htonl(session
[s
].ip
), 0),
3722 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
3724 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
3726 return 1; // RADIUS OK and IP allocated, done...
3730 // This session just got dropped on us by the master or something.
3731 // Make sure our tables up up to date...
3733 int load_session(sessionidt s
, sessiont
*new)
3739 if (new->ip_pool_index
>= MAXIPPOOL
||
3740 new->tunnel
>= MAXTUNNEL
)
3742 LOG(0, s
, 0, "Strange session update received!\n");
3743 // FIXME! What to do here?
3748 // Ok. All sanity checks passed. Now we're committed to
3749 // loading the new session.
3752 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
3754 // See if routes/ip cache need updating
3755 if (new->ip
!= session
[s
].ip
)
3758 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
3759 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
3760 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
3768 // remove old routes...
3769 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
3771 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
3772 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
3775 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
3781 if (session
[s
].ip_pool_index
== -1) // static IP
3783 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
3785 else // It's part of the IP pool, remove it manually.
3786 uncache_ipmap(session
[s
].ip
);
3791 // add new routes...
3792 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
3794 if ((new->ip
& new->route
[i
].mask
) ==
3795 (new->route
[i
].ip
& new->route
[i
].mask
))
3798 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
3804 // If there's a new one, add it.
3805 if (new->ip_pool_index
== -1)
3807 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
3810 cache_ipmap(new->ip
, s
);
3815 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
3817 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %d\n", (int) new->filter_in
);
3821 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
3823 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %d\n", (int) new->filter_out
);
3824 new->filter_out
= 0;
3827 if (new->filter_in
!= session
[s
].filter_in
)
3829 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
3830 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
3833 if (new->filter_out
!= session
[s
].filter_out
)
3835 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
3836 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
3839 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
3840 // for walking the sessions to forward byte counts to the master.
3841 config
->cluster_highest_sessionid
= s
;
3843 // TEMP: old session struct used a u32 to define the throttle
3844 // speed for both up/down, new uses a u16 for each. Deal with
3845 // sessions from an old master for migration.
3846 if (new->throttle_out
== 0 && new->tbf_out
)
3847 new->throttle_out
= new->throttle_in
;
3849 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
3851 // Do fixups into address pool.
3852 if (new->ip_pool_index
!= -1)
3853 fix_address_pool(s
);
3858 static void initplugins()
3862 loaded_plugins
= ll_init();
3863 // Initialize the plugins to nothing
3864 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
3865 plugins
[i
] = ll_init();
3868 static void *open_plugin(char *plugin_name
, int load
)
3870 char path
[256] = "";
3872 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
3873 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
3874 return dlopen(path
, RTLD_NOW
);
3877 // plugin callback to get a config value
3878 static void *getconfig(char *key
, enum config_typet type
)
3882 for (i
= 0; config_values
[i
].key
; i
++)
3884 if (!strcmp(config_values
[i
].key
, key
))
3886 if (config_values
[i
].type
== type
)
3887 return ((void *) config
) + config_values
[i
].offset
;
3889 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
3890 key
, type
, config_values
[i
].type
);
3896 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
3900 static int add_plugin(char *plugin_name
)
3902 static struct pluginfuncs funcs
= {
3907 sessiontbysessionidt
,
3908 sessionidtbysessiont
,
3914 cluster_send_session
,
3917 void *p
= open_plugin(plugin_name
, 1);
3918 int (*initfunc
)(struct pluginfuncs
*);
3923 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
3927 if (ll_contains(loaded_plugins
, p
))
3930 return 0; // already loaded
3934 int *v
= dlsym(p
, "plugin_api_version");
3935 if (!v
|| *v
!= PLUGIN_API_VERSION
)
3937 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
3943 if ((initfunc
= dlsym(p
, "plugin_init")))
3945 if (!initfunc(&funcs
))
3947 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
3953 ll_push(loaded_plugins
, p
);
3955 for (i
= 0; i
< max_plugin_functions
; i
++)
3958 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3960 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
3961 ll_push(plugins
[i
], x
);
3965 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
3969 static void run_plugin_done(void *plugin
)
3971 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
3977 static int remove_plugin(char *plugin_name
)
3979 void *p
= open_plugin(plugin_name
, 0);
3985 if (ll_contains(loaded_plugins
, p
))
3988 for (i
= 0; i
< max_plugin_functions
; i
++)
3991 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
3992 ll_delete(plugins
[i
], x
);
3995 ll_delete(loaded_plugins
, p
);
4001 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
4005 int run_plugins(int plugin_type
, void *data
)
4007 int (*func
)(void *data
);
4009 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
4010 return PLUGIN_RET_ERROR
;
4012 ll_reset(plugins
[plugin_type
]);
4013 while ((func
= ll_next(plugins
[plugin_type
])))
4017 if (r
!= PLUGIN_RET_OK
)
4018 return r
; // stop here
4021 return PLUGIN_RET_OK
;
4024 static void plugins_done()
4028 ll_reset(loaded_plugins
);
4029 while ((p
= ll_next(loaded_plugins
)))
4033 static void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
, int alen
)
4035 struct nsctl request
;
4036 struct nsctl response
;
4037 int type
= unpack_control(&request
, buf
, len
);
4041 if (log_stream
&& config
->debug
>= 4)
4045 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4046 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
4050 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4051 dump_control(&request
, log_stream
);
4057 case NSCTL_REQ_LOAD
:
4058 if (request
.argc
!= 1)
4060 response
.type
= NSCTL_RES_ERR
;
4062 response
.argv
[0] = "name of plugin required";
4064 else if ((r
= add_plugin(request
.argv
[0])) < 1)
4066 response
.type
= NSCTL_RES_ERR
;
4068 response
.argv
[0] = !r
4069 ? "plugin already loaded"
4070 : "error loading plugin";
4074 response
.type
= NSCTL_RES_OK
;
4080 case NSCTL_REQ_UNLOAD
:
4081 if (request
.argc
!= 1)
4083 response
.type
= NSCTL_RES_ERR
;
4085 response
.argv
[0] = "name of plugin required";
4087 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
4089 response
.type
= NSCTL_RES_ERR
;
4091 response
.argv
[0] = !r
4092 ? "plugin not loaded"
4093 : "plugin not found";
4097 response
.type
= NSCTL_RES_OK
;
4103 case NSCTL_REQ_HELP
:
4104 response
.type
= NSCTL_RES_OK
;
4107 ll_reset(loaded_plugins
);
4108 while ((p
= ll_next(loaded_plugins
)))
4110 char **help
= dlsym(p
, "plugin_control_help");
4111 while (response
.argc
< 0xff && help
&& *help
)
4112 response
.argv
[response
.argc
++] = *help
++;
4117 case NSCTL_REQ_CONTROL
:
4119 struct param_control param
= {
4120 config
->cluster_iam_master
,
4127 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
4129 if (r
== PLUGIN_RET_ERROR
)
4131 response
.type
= NSCTL_RES_ERR
;
4133 response
.argv
[0] = param
.additional
4135 : "error returned by plugin";
4137 else if (r
== PLUGIN_RET_NOTMASTER
)
4139 static char msg
[] = "must be run on master: 000.000.000.000";
4141 response
.type
= NSCTL_RES_ERR
;
4143 if (config
->cluster_master_address
)
4145 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
4146 response
.argv
[0] = msg
;
4150 response
.argv
[0] = "must be run on master: none elected";
4153 else if (!(param
.response
& NSCTL_RESPONSE
))
4155 response
.type
= NSCTL_RES_ERR
;
4157 response
.argv
[0] = param
.response
4158 ? "unrecognised response value from plugin"
4159 : "unhandled action";
4163 response
.type
= param
.response
;
4165 if (param
.additional
)
4168 response
.argv
[0] = param
.additional
;
4176 response
.type
= NSCTL_RES_ERR
;
4178 response
.argv
[0] = "error unpacking control packet";
4181 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
4184 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4188 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
4191 sendto(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
);
4192 if (log_stream
&& config
->debug
>= 4)
4194 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
4195 dump_control(&response
, log_stream
);
4199 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4200 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
4205 static tunnelidt
new_tunnel()
4208 for (i
= 1; i
< MAXTUNNEL
; i
++)
4210 if (tunnel
[i
].state
== TUNNELFREE
)
4212 LOG(4, 0, i
, "Assigning tunnel ID %d\n", i
);
4213 if (i
> config
->cluster_highest_tunnelid
)
4214 config
->cluster_highest_tunnelid
= i
;
4218 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4223 // We're becoming the master. Do any required setup..
4225 // This is principally telling all the plugins that we're
4226 // now a master, and telling them about all the sessions
4227 // that are active too..
4229 void become_master(void)
4232 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
4234 // running a bunch of iptables commands is slow and can cause
4235 // the master to drop tunnels on takeover--kludge around the
4236 // problem by forking for the moment (note: race)
4237 if (!fork_and_close())
4239 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4241 if (!session
[s
].tunnel
) // Not an in-use session.
4244 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
4250 for (i
= 0; i
< config
->num_radfds
; i
++)
4252 FD_SET(radfds
[i
], &readset
);
4253 if (radfds
[i
] > readset_n
)
4254 readset_n
= radfds
[i
];
4258 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4264 if (CLI_HELP_REQUESTED
)
4265 return CLI_HELP_NO_ARGS
;
4268 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4270 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4273 if (!session
[s
].tunnel
)
4276 idle
= time_now
- session
[s
].last_packet
;
4277 idle
/= 5 ; // In multiples of 5 seconds.
4287 for (i
= 0; i
< 63; ++i
)
4289 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4291 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
4292 cli_print(cli
, "%d total sessions open.", count
);
4296 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
4302 if (CLI_HELP_REQUESTED
)
4303 return CLI_HELP_NO_ARGS
;
4306 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
4308 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
4311 if (!session
[s
].tunnel
)
4314 d
= time_now
- session
[s
].opened
;
4317 while (d
> 1 && open
< 32)
4327 for (i
= 0; i
< 30; ++i
)
4329 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
4332 cli_print(cli
, "%d total sessions open.", count
);
4338 * This unencodes the AVP using the L2TP CHAP secret and the
4339 * previously stored random vector. It replaces the hidden data with
4340 * the cleartext data and returns the length of the cleartext data
4341 * (including the AVP "header" of 6 bytes).
4343 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4345 static int unhide_avp(u8
*avp
, tunnelidt t
, sessionidt s
, u16 length
)
4350 u8 working_vector
[16];
4351 uint16_t hidden_length
;
4356 // Find the AVP type.
4357 type
[0] = *(avp
+ 4);
4358 type
[1] = *(avp
+ 5);
4360 // Line up with the hidden data
4361 cursor
= output
= avp
+ 6;
4363 // Compute initial pad
4365 MD5Update(&ctx
, type
, 2);
4366 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4367 MD5Update(&ctx
, session
[s
].random_vector
, session
[s
].random_vector_length
);
4368 MD5Final(digest
, &ctx
);
4370 // Get hidden length
4371 hidden_length
= ((uint16_t) (digest
[0] ^ cursor
[0])) * 256 + (uint16_t) (digest
[1] ^ cursor
[1]);
4373 // Keep these for later use
4374 working_vector
[0] = *cursor
;
4375 working_vector
[1] = *(cursor
+ 1);
4378 if (hidden_length
> length
- 8)
4380 LOG(1, s
, t
, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length
, (int) length
);
4384 /* Decrypt remainder */
4386 todo
= hidden_length
;
4389 working_vector
[done
] = *cursor
;
4390 *output
= digest
[done
] ^ *cursor
;
4395 if (done
== 16 && todo
)
4397 // Compute new digest
4400 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
4401 MD5Update(&ctx
, &working_vector
, 16);
4402 MD5Final(digest
, &ctx
);
4406 return hidden_length
+ 6;
4409 static int ip_filter_port(ip_filter_portt
*p
, portt port
)
4413 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
4414 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
4415 case FILTER_PORT_OP_GT
: return port
> p
->port
;
4416 case FILTER_PORT_OP_LT
: return port
< p
->port
;
4417 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
4423 static int ip_filter_flag(u8 op
, u8 sflags
, u8 cflags
, u8 flags
)
4427 case FILTER_FLAG_OP_ANY
:
4428 return (flags
& sflags
) || (~flags
& cflags
);
4430 case FILTER_FLAG_OP_ALL
:
4431 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
4433 case FILTER_FLAG_OP_EST
:
4434 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
4440 int ip_filter(u8
*buf
, int len
, u8 filter
)
4449 ip_filter_rulet
*rule
;
4451 if (len
< 20) // up to end of destination address
4454 if ((*buf
>> 4) != 4) // IPv4
4457 frag_offset
= ntohs(*(u16
*) (buf
+ 6)) & 0x1fff;
4459 src_ip
= *(u32
*) (buf
+ 12);
4460 dst_ip
= *(u32
*) (buf
+ 16);
4462 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
4464 int l
= (buf
[0] & 0xf) * 4; // length of IP header
4465 if (len
< l
+ 4) // ports
4468 src_port
= ntohs(*(u16
*) (buf
+ l
));
4469 dst_port
= ntohs(*(u16
*) (buf
+ l
+ 2));
4470 if (proto
== IPPROTO_TCP
)
4472 if (len
< l
+ 14) // flags
4475 flags
= buf
[l
+ 13] & 0x3f;
4479 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
4481 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
4484 if (rule
->src_wild
!= INADDR_BROADCAST
&&
4485 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
4488 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
4489 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
4494 if (!rule
->frag
|| rule
->action
== FILTER_ACTION_DENY
)
4502 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
4504 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
4507 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
4510 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
4511 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
4518 return rule
->action
== FILTER_ACTION_PERMIT
;