lib/Net/ISP/Balance.pm

filter: Statementstmt 65.9% 470 / 713 Branchbran 44.8% 121 / 270 Conditioncond 43.7% 35 / 80 MC/DCmcdc 8.5% 4 / 47 Subroutinesub 69.0% 69 / 100 Podpod 85.2% 58 / 68 totaltotal 59.2% 757 / 1278 CC 212 SCAR 28.0
CC
212
Cov
59%
save_routing_and_firewall
90.0
restore_routing_and_firewall
90.0
event
72.0
CRAP 16.5
« blib/lib/Net/ISP/Balance/ConfigData.pm ↑ Summary blib/lib/Net/ISP/Balance.pm »
1 package Net::ISP::Balance;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use Fcntl ':flock';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Carp 'croak','carp';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 2 ▶eval 'use Net::Netmask';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶eval 'use Net::ISP::Balance::ConfigData';
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 2 our $VERSION = '1.20';
12  
13 =head1 NAME
14  
15 Net::ISP::Balance - Support load balancing across multiple internet service providers
16  
17 =head1 SYNOPSIS
18  
19 use Net::ISP::Balance;
20  
21 # initialize the module with its configuration file
22 my $bal = Net::ISP::Balance->new('/etc/network/balance.conf');
23  
24 $bal->verbose(1); # verbosely print routing and firewall
25 # commands to STDERR before running them.
26 $bal->echo_only(1); # echo commands to STDOUT; don't execute them.
27  
28 # mark the balanced services that are up
29 $bal->up('CABLE','DSL','SATELLITE');
30  
31 # write out routing and firewall commands
32 $bal->set_routes_and_firewall();
33  
34 # write out a forwarding rule
35 $bal->forward(80 => '192.168.10.35'); # forward web requests to this host
36  
37 # write out an arbitrary routing rule
38 $bal->ip_route('add 192.168.100.1 dev eth0 src 198.162.1.14');
39  
40 # write out an arbitrary iptables rule
41 $bal->iptables('-A INCOMING -p tcp --dport 6000 -j REJECT');
42  
43 # get information about all services
44 my @s = $bal->service_names;
45 for my $s (@s) {
46 print $bal->dev($s);
47 print $bal->ip($s);
48 print $bal->gw($s);
49 print $bal->net($s);
50 print $bal->fwmark($s);
51 print $bal->table($s);
52 print $bal->running($s);
53 print $bal->weight($s);
54 }
55  
56 =cut
57  
58 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
59  
60 =head1 USAGE
61  
62 This library supports load_balance.pl, a script to load-balance a home
63 network across two or more Internet Service Providers (ISP). The
64 load_balance.pl script can be found in the bin subdirectory of this
65 distribution. Installation and configuration instructions can be found
66 at http://lstein.github.io/Net-ISP-Balance/.
67  
68 =head1 CONFIGURATION FILE
69  
70 This module reads a configuration file with the following format:
71  
72 #service device role ping-ip weight
73 CABLE eth0 isp 173.194.43.95 1
74 DSL ppp0 isp 173.194.43.95 1
75 LAN1 eth1 lan
76 LAN2 eth2 lan
77 LAN3 eth3 lan
78  
79  
80 The first column is a service name that is used to bring up or down
81 the needed routes and firewall rules.
82  
83 The second column is the name of the network interface device that
84 connects to that service.
85  
86 The third column is either "isp" or "lan". There may be any number of
87 these. The script will firewall traffic passing through any of the
88 ISPs, and will load balance traffic among them. Traffic can flow
89 freely among any of the interfaces marked as belonging to a LAN.
90  
91 The fourth column is the IP address of a host that can be periodically
92 pinged to test the integrity of each ISP connection. If too many pings
93 failed, the service will be brought down and all traffic routed
94 through the remaining ISP(s). The service will continue to be
95 monitored and will be brought up when it is once again working. Choose
96 a host that is not likely to go offline for reasons unrelated to your
97 network connectivity, such as google.com, or the ISP's web site. If
98 this column is absent, then the host will default to www.google.ca,
99 which is probably not what you want!
100  
101 The fifth column (optional) is a weight to assign to the service, and
102 is only valid for ISP rows. If weights are equal, traffic will be
103 apportioned evenly between the two routes. Increase a weight to favor
104 one ISP over the others. For example, if "CABLE" has a weight of 2 and
105 "DSL" has a weight of 1, then twice as much traffic will flow through
106 the CABLE service. If this column is omitted, then equal weights are
107 assumed.
108  
109 If this package is running on a single Internet-connected host, not a
110 router, then do not include a "lan" line.
111  
112 In addition to the main table, there are several configuration options
113 that follow the format "configuration_name=value":
114  
115 =over 4
116  
117 =item forwarding_group=<space-delimited list of services>
118  
119 The forwarding_group configuration option defines a set of services
120 that the router is allowed to forward packets among. Provide a
121 space-delimited set of service names or one or more of the
122 abbreviations ":isp" and ":lan". ":isp" is an abbreviation for all
123 ISP services, while ":lan" is an abbreviation for all LAN services. So
124 for example, the two configuration lines below will allow forwarding
125 of packets between LAN1, LAN2, LAN3 and both ISPs. LAN4 will be
126 granted access to both ISPs but won't be able to exchange packets with
127 LANs 1 through 3:
128  
129 forwarding_group=LAN1 LAN2 LAN3 :isp
130 forwarding_group=LAN4 :isp
131  
132 If no forwarding_group options are defined, then the router will
133 forward packets among all LANs and ISP interfaces. It is equivalent to
134 this:
135  
136 forwarding_group=:lan :isp
137  
138 =item warn_email=<email address>
139  
140 Warn_email provides an email address to send notification messages to
141 if the status of a link changes (goes down, or comes back up). You
142 must have the "mail" program installed and configured for this to
143 work.
144  
145 =item interval_ms=<integer>
146  
147 Indicates how often to check the ping host for each ISP.
148  
149 =item min_packet_loss=<integer>
150  
151 =item max_packet_loss=<integer>
152  
153 These define the minimum and maximum packet losses required to declare
154 a link up or down.
155  
156 =item min_successive_pkts_rcvd=<integer>
157  
158 =item max_successive_pkts_recvd=<integer>
159  
160 These define the minimum and maximum numbers of
161 successively-transmitted pings that must be returned in order to
162 declare a link up or down.
163  
164 =item long_down_time=<integer>
165  
166 This is a value in seconds after a service that has gone down is
167 considered to have been down for a long time. You may optionally run a
168 series of shell scripts when this has occurred (see below).
169  
170 =back
171  
172 =head1 FREQUENTLY-USED METHODS
173  
174 Here are the class methods for this module that can be called on the
175 class name.
176  
177 =head2 $bal = Net::ISP::Balance->new('/path/to/config_file.conf');
178  
179 Creates a new balancer object.
180  
181 The first optional argument is the balancer configuration file, which
182 defaults to /etc/network/balance.conf on Ubuntu/Debian-derived
183 systems, and /etc/sysconfig/network-scripts/balance.conf on
184 RedHat/CentOS-derived systems. From hereon, we'll refer to the base of
185 the various configuration files as $ETC_NETWORK.
186  
187 =cut
188  
189 sub new {
190 1 ▶ my $class = shift;
Subroutine new: called CC=5 SCAR=17.8
Pod documented
191 1 my ($conf,%options) = @_;
192 1 ▶ $conf ||= $class->default_conf_file;
Condition33%1/3
$conf ||= $class->default_conf_file
l!l&&r!l&&!r
100
MC/DC0%0/2
$conf ||= $class->default_conf_file
$conf $class->default_conf_file
Truth table33%1/3
A ||= B
A= $confB= $class->default_conf_file
ABresult
1X1
011
000
193 1 ▶ $conf && -r $conf || croak 'Must provide a readable configuration file path';
Branch: 1 branch
BranchTrueFalseTotal
$conf and -r $conf or croak("Must provide a readable configuration file path") 0 1 1
Condition33%1/3
$conf and -r $conf
!ll&&!rl&&r
001
MC/DC0%0/2
$conf and -r $conf
$conf -r $conf
Truth table33%1/3
A and B
A= $confB= -r $conf
ABresult
0X0
100
111
194 my $self = bless {
195 verbose => 0,
196 echo_only => 0,
197 services => {},
198 rules_directory => $class->default_rules_directory,
199 lsm_conf_file => $class->default_lsm_conf_file,
200 lsm_scripts_dir => $class->default_lsm_scripts_dir,
201 bal_conf_file => $conf,
202 keep_custom_chains => 1,
203 dummy_data => $options{dummy_test_data},
204 dev_lookup_retries => $options{dev_lookup_retries},
205 dev_lookup_retry_delay => $options{dev_lookup_retry_delay},
206 1 ▶ },ref $class || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
010
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
207  
208 1 $self->_parse_configuration_file($conf);
209  
210 # Instead of potentially timing out on new(), we collect information on all
211 # interfaces that are currently up. We do this again with the timeout before
212 # actually changing the routing table, when it is critical that all interfaces
213 # be configured.
214 # $self->_collect_interfaces_retry(); # try to collect interfaces over 10 seconds
215 1 my %ifs;
216 1 $self->_collect_interfaces(\%ifs);
217 1 $self->{services} = \%ifs;
218  
219 1 return $self;
220 }
221  
222 =head2 $bal->set_routes_and_firewall
223  
224 Once the Balance objecty is created, call set_routes_and_firewall() to
225 configure the routing tables and firewall for load balancing. These
226 rules will either be executed on the system, or printed to standard
227 output as a series of shell script commands if echo_only() is set to
228 true.
229  
230 The routing tables and firewall rules are based on the configuration
231 described in $ETC_NETWORK/balance.conf. You may add custom routes and
232 rules by creating files in $ETC_NETWORK/balance/routes and
233 $ETC_NETWORK/balance/firewall. The former contains a series of files
234 or perl scripts that define additional routing rules. The latter
235 contains files or perl scripts that define additional firewall rules.
236  
237 Files located in $ETC_NETWORK/balance/pre-run will be executed AFTER
238 load_balance.pl has cleared the routing table and firewall, but before
239 it has emitted any any route/firewall commands. Files located in
240 in $ETC_NETWORK/balance/post-run will be run after load_balance.pl is
241 finished.
242  
243 Any files you put into these directories will be read in alphabetic
244 order and added to the routes and/or firewall rules emitted by the
245 load balancing script.Contained in this directory are subdirectories named "routes" and
246 "firewall". The former contains a series of files or perl scripts that
247 define additional routing rules. The latter contains files or perl
248 scripts that define additional firewall rules.
249  
250 Note that files ending in ~ or starting with # are treated as autosave files
251 and ignored.
252  
253 A typical routing rules file will look like the example shown
254 below.
255  
256 # file: /etc/network/balance/01.my_routes
257 ip route add 192.168.100.1 dev eth0 src 198.162.1.14
258 ip route add 192.168.1.0/24 dev eth2 src 10.0.0.4
259  
260 Each line will be sent to the shell, and it is intended (but not
261 required) that these be calls to the "ip" command. General shell
262 scripting constructs are not allowed here.
263  
264 A typical firewall rules file will look like the example shown here:
265  
266 # file: /etc/network/firewall/01.my_firewall_rules
267  
268 # accept incoming telnet connections to the router
269 iptable -A INPUT -p tcp --syn --dport telnet -j ACCEPT
270  
271 # masquerade connections to the DSL modem's control interface
272 iptables -t nat -A POSTROUTING -o eth2 -j MASQUERADE
273  
274 You may also insert routing and firewall rules via fragments of Perl
275 code, which is convenient because you don't have to hard-code any
276 network addresses and can make use of a variety of shortcuts. To do
277 this, simply end the file's name with .pl and make it executable.
278  
279 Here's an example that defines a series of port forwarding rules for
280 incoming connections:
281  
282 # file: /etc/network/firewall/02.forwardings.pl
283  
284 $B->forward(80 => '192.168.10.35'); # forward port 80 to internal web server
285 $B->forward(443=> '192.168.10.35'); # forward port 443 to
286 $B->forward(23 => '192.168.10.35:22'); # forward port 23 to ssh on web sever
287  
288 The main thing to know is that on entry to the script the global
289 variable $B will contain an initialized instance of a
290 Net::ISP::Balance object. You may then make method calls on this
291 object to emit firewall and routing rules.
292  
293 A typical routing rules file will look like the example shown
294 below.
295  
296 # file: /etc/network/balance/01.my_routes
297 ip route add 192.168.100.1 dev eth0 src 198.162.1.14
298 ip route add 192.168.1.0/24 dev eth2 src 10.0.0.4
299  
300 Each line will be sent to the shell, and it is intended (but not
301 required) that these be calls to the "ip" command. General shell
302 scripting constructs are not allowed here.
303  
304 A typical firewall rules file will look like the example shown here:
305  
306 # file: /etc/network/firewall/01.my_firewall_rules
307  
308 # accept incoming telnet connections to the router
309 iptable -A INPUT -p tcp --syn --dport telnet -j ACCEPT
310  
311 # masquerade connections to the DSL modem's control interface
312 iptables -t nat -A POSTROUTING -o eth2 -j MASQUERADE
313  
314 You may also insert routing and firewall rules via fragments of Perl
315 code, which is convenient because you don't have to hard-code any
316 network addresses and can make use of a variety of shortcuts. To do
317 this, simply end the file's name with .pl and make it executable.
318  
319 Here's an example that defines a series of port forwarding rules for
320 incoming connections:
321  
322 # file: /etc/network/firewall/02.forwardings.pl
323  
324 $B->forward(80 => '192.168.10.35'); # forward port 80 to internal web server
325 $B->forward(443=> '192.168.10.35'); # forward port 443 to
326 $B->forward(23 => '192.168.10.35:22'); # forward port 23 to ssh on web sever
327  
328 The main thing to know is that on entry to the script the global
329 variable $B will contain an initialized instance of a
330 Net::ISP::Balance object. You may then make method calls on this
331 object to emit firewall and routing rules.
332  
333 =cut
334  
335 sub set_routes_and_firewall {
336 0 ▶ my $self = shift;
Subroutine set_routes_and_firewall: not called CC=3 SCAR=24.8
Pod documented
337  
338 0 $self->save_routing_and_firewall();
339  
340 # first disable forwarding and clear the routing and firewall tables
341 0 $self->enable_forwarding(0);
342 0 $self->_initialize_routes();
343 0 $self->_initialize_firewall();
344 0 $self->pre_run_rules();
345 0 $self->_collect_interfaces_retry();
346 0 ▶ if ($self->isp_services) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->isp_services) { } 0 0 0
347 0 $self->set_routes();
348 0 $self->set_firewall();
349 0 $self->enable_forwarding(1);
350 0 $self->post_run_rules();
351 } else {
352 0 warn "No ISP services seem to be up. Restoring routing tables and firewall.\n";
353 0 ▶ $self->restore_routing_and_firewall() unless $self->echo_only;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->echo_only 0 0 0
354 0 return;
355 }
356 }
357  
358 sub save_routing_and_firewall {
359 0 ▶ my $self = shift;
Subroutine save_routing_and_firewall: not called CC=9 SCAR=45.0
Pod undocumented
360  
361 0 $self->{stored_routes} = [];
362 0 $self->{stored_rules} = '';
363 0 $self->{stored_firewall} = '';
364  
365 0 ▶ open my $f,"ip route show table all|" or die $!; # binary
Branch: 1 branch
BranchTrueFalseTotal
open my $f, "ip route show table all|" or die $! 0 0 0
366 0 ▶ while (<$f>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $f)) 0 0 0
367 0 chomp;
368 0 ▶ next if /unreachable/;
Branch: 1 branch
BranchTrueFalseTotal
if /unreachable/ 0 0 0
369 0 ▶ next if /proto none/;
Branch: 1 branch
BranchTrueFalseTotal
if /proto none/ 0 0 0
370 0 unshift @{$self->{stored_routes}},$_;
371 }
372 0 close $f;
373  
374 0 ▶ open $f,"ip rule show|" or die $!; # text
Branch: 1 branch
BranchTrueFalseTotal
open $f, "ip rule show|" or die $! 0 0 0
375 0 ▶ while (<$f>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $f)) 0 0 0
376 0 $self->{stored_rules} .= $_;
377 }
378 0 close $f;
379  
380 0 ▶ open $f,"iptables-save|" or die $!; # text
Branch: 1 branch
BranchTrueFalseTotal
open $f, "iptables-save|" or die $! 0 0 0
381 0 ▶ while (<$f>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $f)) 0 0 0
382 0 $self->{stored_firewall} .= $_;
383 }
384 0 close $f;
385 }
386  
387 sub restore_routing_and_firewall {
388 0 ▶ my $self = shift;
Subroutine restore_routing_and_firewall: not called CC=9 SCAR=45.0
Pod undocumented
389  
390 0 $self->_initialize_routes();
391 0 ▶ if ($self->{stored_routes}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stored_routes"}) 0 0 0
392 0 for (@{$self->{stored_routes}}) {
393 0 $self->ip_route("add $_");
394 }
395 }
396  
397 0 ▶ if ($self->{stored_rules}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stored_rules"}) 0 0 0
398 0 my @rules = split "\n",$self->{stored_rules};
399 0 for my $r (@rules) {
400 0 my ($priority,$rule) = $r =~ /^(\d+):\s*(.+)/;
401 0 ▶ next if $priority == 32766; # these are created by _initialize!
Branch: 1 branch
BranchTrueFalseTotal
if $priority == 32766 0 0 0
402 0 ▶ next if $priority == 32767;
Branch: 1 branch
BranchTrueFalseTotal
if $priority == 32767 0 0 0
403 0 $self->ip_rule('add',$rule,"priority $priority");
404 }
405 }
406  
407 0 ▶ if ($self->{stored_firewall}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stored_firewall"}) 0 0 0
408 0 ▶ open my $f,"|iptables-restore" or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $f, "|iptables-restore" or die $! 0 0 0
409 0 print $f $self->{stored_firewall};
410 0 close $f;
411 }
412 }
413  
414 =head2 $verbose = $bal->verbose([boolean]);
415  
416 sub bal_conf_file { my $self = shift; my $d = $self->{bal_conf_file};
417 $self->{bal_conf_file} = shift if @_; $d; } Get/set verbosity of
418 the module. If verbose is true, then firewall and routing rules
419 will be echoed to STDERR before being executed on the system.
420  
421 =cut
422  
423 sub verbose {
424 175 ▶ my $self = shift;
Subroutine verbose: called CC=2 SCAR=7.0
Pod documented
425 175 my $d = $self->{verbose};
426 175 ▶ $self->{verbose} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 175 175
427 175 $d;
428 }
429  
430 =head2 $echo = $bal->echo_only([boolean]);
431  
432 Get/set the echo_only flag. If this is true (default false), then
433 routing and firewall rules will be printed to STDOUT rathar than being
434 executed.
435  
436 =cut
437  
438 sub echo_only {
439 158 ▶ my $self = shift;
Subroutine echo_only: called CC=2 SCAR=6.9
Pod documented
440 158 my $d = $self->{echo_only};
441 158 ▶ $self->{echo_only} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 157 158
442 158 $d;
443 }
444  
445 =head2 $retries = $bal->dev_lookup_retries([$retries])
446  
447 Get/set the number of times the library will try to look up an interface
448 that is not up or does not have an IP address. Default is 10
449  
450 =cut
451  
452 sub dev_lookup_retries {
453 0 ▶ my $self = shift;
Subroutine dev_lookup_retries: not called CC=3 SCAR=24.8
Pod documented
454 0 ▶ my $d = $self->{dev_lookup_retries} || 10;
Condition0%0/2
$self->{'dev_lookup_retries'} || 10
l!l
00
MC/DC0%0/1
$self->{'dev_lookup_retries'} || 10
$self->{'dev_lookup_retries'}
Truth table0%0/2
A
A= $self->{'dev_lookup_retries'}
Aresult
11
00
455 0 ▶ $self->{dev_lookup_retries} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
456 0 $d;
457 }
458  
459 =head2 $seconds = $bal->dev_lookup_retry_delay([$seconds])
460  
461 Get/set the number of seconds between retries when an interface is not up
462 or is missing an IP address. Default is 1.
463  
464 =cut
465  
466 sub dev_lookup_retry_delay {
467 0 ▶ my $self = shift;
Subroutine dev_lookup_retry_delay: not called CC=3 SCAR=24.8
Pod documented
468 0 ▶ my $d = $self->{dev_lookup_retry_delay} || 1;
Condition0%0/2
$self->{'dev_lookup_retry_delay'} || 1
l!l
00
MC/DC0%0/1
$self->{'dev_lookup_retry_delay'} || 1
$self->{'dev_lookup_retry_delay'}
Truth table0%0/2
A
A= $self->{'dev_lookup_retry_delay'}
Aresult
11
00
469 0 ▶ $self->{dev_lookup_retry_delay} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
470 0 $d;
471 }
472  
473 =head2 $boolean = $bal->keep_custom_chains([boolean]);
474  
475 Get/set the keep_custom_chains flag. If this is true (default), then
476 any custom iptables chains, such as those created by miniunpnpd or
477 fail2ban, will be restored after execution of the firewall rules. If
478 false, then these rules were be flushed.
479  
480 =cut
481  
482 sub keep_custom_chains {
483 0 ▶ my $self = shift;
Subroutine keep_custom_chains: not called CC=2 SCAR=17.9
Pod documented
484 0 my $d = $self->{keep_custom_chains};
485 0 ▶ $self->{keep_custom_chains} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
486 0 $d;
487 }
488  
489 =head2 $result_code = $bal->sh(@args)
490  
491 Pass @args to the shell for execution. If echo_only() is set to true,
492 the command will not be executed, but instead be printed to standard
493 output.
494  
495 Example:
496  
497 $bal->sh('ip rule flush');
498  
499 The result code is the same as CORE::system().
500  
501 =cut
502  
503 sub sh {
504 157 ▶ my $self = shift;
Subroutine sh: called CC=3 SCAR=11.3
Pod documented
505 157 my @args = @_;
506 157 my $arg = join ' ',@args;
507 157 chomp($arg);
508 157 ▶ carp $arg if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 157 157
509 157 ▶ if ($self->echo_only) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->echo_only) { } 157 0 157
510 157 $arg .= "\n";
511 157 print $arg;
512 } else {
513 0 system $arg;
514 }
515 }
516  
517 =head2 $bal->iptables(@args)
518  
519 Invoke sh() to call "iptables @args".
520  
521 Example:
522  
523 $bal->iptables('-A OUTPUT -o eth0 -j DROP');
524  
525 You may pass an array reference to iptables(), in which case iptables
526 is called on each member of the array in turn.
527  
528 Example:
529  
530 $bal->iptables(['-P OUTPUT DROP',
531 '-P INPUT DROP',
532 '-P FORWARD DROP']);
533  
534 Note that the method keeps track of rules; if you try to enter the
535 same iptables rule more than once the redundant ones will be ignored.
536  
537 =cut
538  
539 2 my %seen_rule;
540  
541 sub iptables {
542 130 ▶ my $self = shift;
Subroutine iptables: called CC=5 SCAR=16.1
Pod documented
543 130 ▶ if (ref $_[0] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'ARRAY') { } 4 126 130
544 4 ▶ $seen_rule{$_}++ || $self->sh('iptables',$_) foreach @{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
$seen_rule{$_}++ or $self->sh("iptables", $_) 12 0 12
545 } else {
546 126 ▶ $seen_rule{"@_"}++ || $self->sh('iptables',@_)
Branch: 1 branch
BranchTrueFalseTotal
$seen_rule{join $", @_}++ or $self->sh("iptables", @_) 97 29 126
547 }
548 }
549  
550 sub _iptables_add_rule {
551 13 ▶ my $self = shift;
Subroutine _iptables_add_rule: called CC=7 SCAR=19.7
552 13 my ($operation,$chain,$table,@args) = @_;
553 13 ▶ croak "You must provide a chain name" unless $chain;
Branch: 1 branch
BranchTrueFalseTotal
unless $chain 0 13 13
554 13 ▶ my $op = $operation eq 'append' ? '-A'
Branch: 4 branches
BranchTrueFalseTotal
$operation eq 'append' ? : 2 11 13
$operation eq 'delete' ? : 1 10 11
$operation eq 'check ' ? : 0 10 10
$operation eq 'insert' ? : 10 0 10
555 :$operation eq 'delete' ? '-D'
556 :$operation eq 'check ' ? '-C'
557 :$operation eq 'insert' ? '-I'
558 :'-A';
559
560 13 my $command = '';
561 13 ▶ $command .= "-t $table " if $table;
Branch: 1 branch
BranchTrueFalseTotal
if $table 3 10 13
562 13 $command .= "$op $chain ";
563 13 $command .= $self->_process_iptable_options(@args);
564 13 $self->iptables($command);
565 }
566  
567 sub iptables_append {
568 0 ▶ my $self = shift;
Subroutine iptables_append: not called CC=1 SCAR=6.9
Pod undocumented
569 0 my ($table,$chain,@args) = @_;
570 0 $self->_iptables_add_rule('append',$table,$chain,@args);
571 }
572  
573 sub iptables_delete {
574 0 ▶ my $self = shift;
Subroutine iptables_delete: not called CC=1 SCAR=6.9
Pod undocumented
575 0 my ($table,$chain,@args) = @_;
576 0 $self->_iptables_add_rule('delete',$table,$chain,@args);
577 }
578  
579 sub iptables_check {
580 0 ▶ my $self = shift;
Subroutine iptables_check: not called CC=1 SCAR=6.9
Pod undocumented
581 0 my ($table,$chain,@args) = @_;
582 0 $self->_iptables_add_rule('check',$table,$chain,@args);
583 }
584  
585 sub iptables_insert {
586 0 ▶ my $self = shift;
Subroutine iptables_insert: not called CC=1 SCAR=6.9
Pod undocumented
587 0 my ($table,$chain,@args) = @_;
588 0 $self->_iptables_add_rule('insert',$table,$chain,@args);
589 }
590  
591 =head2 $bal->firewall_rule($chain,$table,@args)
592  
593 Issue an iptables firewall rule.
594  
595 $chain -- The chain to apply the rule to, e.g. "INPUT".
596
597 $table -- The table to apply the rule to, e.g. "nat". Undef defaults to
598 the standard "filter" table.
599  
600 @args -- The other arguments to pass to iptables.
601  
602 Here is a typical example of blocking incoming connections to port 25:
603  
604 $bal->firewall_rule(INPUT=>undef,-p=>'tcp',-dport=>25,-j=>'REJECT');
605  
606 This will issue the following command:
607  
608 iptables -A INPUT -p tcp --dport 25 -j REJECT
609  
610 The default operation is to append the rule to the chain using
611 -A. This can be changed by passing $bal->firewall_op() any of the
612 strings "append", "delete", "insert" or "check". Subsequent calls to
613 firewall_rule() will return commands for the indicated function:
614  
615 $bal->firewall_op('delete');
616 $bal->firewall_rule(INPUT=>undef,-p=>'tcp',-dport=>25,-j=>'REJECT');
617 # gives iptables -A INPUT -p tcp --dport 25 -j REJECT
618  
619 If you want to apply a series of deletes and then revert to the
620 original append behavior, then it is easiest to localize the hash key
621 "firewall_op":
622  
623 {
624 local $bal->{firewall_op} = 'delete';
625 $bal->firewall_rule(INPUT=>undef,-dport=>25,-j=>'ACCEPT');
626 $bal->firewall_rule(INPUT->undef,-dport=>80,-j=>'ACCEPT');
627 }
628
629 $bal->firewall_rule(INPUT=>undef,-dport=>25,-j=>'DROP');
630 $bal->firewall_rule(INPUT=>undef,-dport=>80,-j=>'DROP');
631  
632 =cut
633  
634 sub firewall_rule {
635 13 ▶ my $self = shift;
Subroutine firewall_rule: called CC=1 SCAR=0.0
Pod documented
636 13 my ($chain,$table,@args) = @_;
637 13 my $operation = $self->firewall_op();
638 13 $self->_iptables_add_rule($operation,$chain,$table,@args);
639 }
640  
641 sub firewall_op {
642 13 ▶ my $self = shift;
Subroutine firewall_op: called CC=3 SCAR=11.8
Pod undocumented
643 13 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 13 13
644 0 $self->{firewall_op} = shift;
645 0 return;
646 }
647 13 ▶ my $d = $self->{firewall_op} || 'append';
Condition100%2/2
$self->{'firewall_op'} || 'append'
l!l
112
MC/DC100%1/1
$self->{'firewall_op'} || 'append'
$self->{'firewall_op'}
Truth table100%2/2
A
A= $self->{'firewall_op'}
Aresult
11
00
648 13 return $d;
649 }
650  
651 =head2 $bal->force_route($service_or_device,@selectors)
652  
653 The force_route() method issues iptables commands that will force
654 certain traffic to travel over a particular ISP service or network
655 device. This is useful, for example, when one of your ISPs acts as
656 your e-mail relay and only accepts connections from the IP address
657 it assigns.
658  
659 $service_or_device is the symbolic name of an ISP service
660 (e.g. "CABLE") or a network device that a service is attached to
661 (e.g. "eth0").
662  
663 @selectors are a series of options that will be passed to
664 iptables to select the routing of packets. For example, to forward all
665 outgoing mail (destined to port 25) to the "CABLE" ISP, you would
666 write:
667  
668 $bal->force_route('CABLE','-p'=>'tcp','--syn','--dport'=>25);
669  
670 @selectors is a series of optional arguments that will be passed to
671 iptables on the command line. They will simply be space-separated, and
672 so the following is equivalent to the previous example:
673  
674 $bal->force_route('CABLE','-p tcp --syn --dport 25');
675  
676 Bare arguments that begin with a leading hyphen and are followed by
677 two or more alphanumeric characters are automatically converted into
678 double-hyphen arguments. This allows you to simplify commands
679 slightly. The following is equivalent to the previous examples:
680  
681 $bal->force_route('CABLE',-p=>'tcp',-syn,-dport=>25);
682  
683 You can delete force_route rules by setting firewall_op() to 'delete':
684  
685 $bal->firewall_op('delete');
686 $bal->force_route('CABLE',-p=>'tcp',-syn,-dport=>25);
687  
688 =cut
689  
690 sub force_route {
691 2 ▶ my $self = shift;
Subroutine force_route: called CC=2 SCAR=7.0
Pod documented
692 2 my ($service_or_device,@selectors) = @_;
693
694 2 ▶ my $service = $self->_service_or_device($service_or_device)
Branch: 1 branch
BranchTrueFalseTotal
my $service = $self->_service_or_device($service_or_device) or croak("did not recognize $service_or_device as a service or a device") 0 2 2
695 or croak "did not recognize $service_or_device as a service or a device";
696  
697 2 my $dest = $self->mark_table($service);
698 2 my $selectors = $self->_process_iptable_options(@selectors);
699 2 $self->firewall_rule(PREROUTING=>'mangle',$selectors,-j=>$dest);
700 }
701  
702 =head2 $bal->add_route($address => $device, [$masquerade])
703  
704 This method is used to create routing and firewall rules for a network
705 that isn't mentioned in balance.conf. This may be necessary to route
706 to VPNs and/or to the control interfaces of attached modems.
707  
708 The first argument is the network address in CIDR format,
709 e.g. '192.168.2.0/24'. The second is the network interface that the
710 network can be accessed via. The third, optional, argument is a
711 boolean. If true, then firewall rules will be set up to masquerade
712 from the LAN into the attached network.
713  
714 Note that this is pretty limited. If you want to do anything more
715 sophisticated you're better off setting the routes and firewall rules
716 manually.
717  
718 =cut
719  
720 sub add_route {
721 1 ▶ my $self = shift;
Subroutine add_route: called CC=7 SCAR=19.9
Pod documented
722 1 my ($network,$device,$masquerade) = @_;
723 1 ▶ $network && $device or croak "usage: add_network(\$network,\$device,[\$masquerade])";
Branch: 1 branch
BranchTrueFalseTotal
$network and $device or croak("usage: add_network(\$network,\$device,[\$masquerade])") 0 1 1
Condition33%1/3
$network and $device
!ll&&!rl&&r
001
MC/DC0%0/2
$network and $device
$network $device
Truth table33%1/3
A and B
A= $networkB= $device
ABresult
0X0
100
111
724 # add the route to our main table
725 1 $self->ip_route("add $network dev $device");
726 # add the route to each outgoing table
727 1 $self->ip_route("add $network dev $device table $_") for map {$self->table($_)} $self->isp_services;
728
729 # create appropriate firewall rules for the network
730 {
731 1 local $self->{firewall_op} = 'insert';
732 1 $self->firewall_rule(OUTPUT => undef,
733 -o => $device,
734 -d => $network,
735 -j => 'ACCEPT');
736 1 $self->firewall_rule(INPUT => undef,
737 -i => $device,
738 -s => $network,
739 -j => 'ACCEPT');
740 $self->firewall_rule(FORWARD => undef,
741 -i => $self->dev($_),
742 -s => $self->net($_),
743 -o => $device,
744 -d => $network,
745 1 -j => 'ACCEPT') for $self->lan_services;
746 $self->firewall_rule(FORWARD => undef,
747 -i => $device,
748 -s => $network,
749 -o => $self->dev($_),
750 -d => $self->net($_),
751 1 -j => 'ACCEPT') for $self->lan_services;
752 }
753 1 ▶ if ($masquerade) {
Branch: 1 branch
BranchTrueFalseTotal
if ($masquerade) 1 0 1
754 1 $self->firewall_rule(POSTROUTING=>'nat',
755 -d => $network,
756 -o => $device,
757 -j => 'MASQUERADE');
758 }
759 }
760  
761 sub _process_iptable_options {
762 15 ▶ my $self = shift;
Subroutine _process_iptable_options: called CC=3 SCAR=11.0
763 15 my @opt = @_;
764 15 foreach (@opt) {
765 114 ▶ $_ = "-$_" if /^-\w{2,}/; # add an extra hyphen to -arguments
Branch: 1 branch
BranchTrueFalseTotal
if /^-\w{2,}/ 4 110 114
766 114 $_ =~ quotemeta($_);
767 }
768 15 return join ' ',@opt;
769 }
770  
771 sub _mark {
772 22 ▶ my $self = shift;
Subroutine _mark: called CC=1 SCAR=0.0
773 22 my $service = shift;
774 22 return "MARK-${service}";
775 }
776  
777 =head2 $table_name = $bal->mark_table($service)
778  
779 This returns the iptables table name for connections marked for output
780 on a particular ISP service. The name is simply the word "MARK-"
781 appended to the service name. For example, for a service named "DSL",
782 the corresponding firewall table will be named "MARK-DSL".
783  
784 =cut
785  
786 22 ▶sub mark_table { shift->_mark(shift) }
Subroutine mark_table: called CC=1 SCAR=0.0
Pod documented
787  
788 sub _service_or_device {
789 2 ▶ my $self = shift;
Subroutine _service_or_device: called CC=2 SCAR=9.2
790 2 my $sod = shift;
791 2 ▶ return $sod if $self->dev($sod);
Branch: 1 branch
BranchTrueFalseTotal
if $self->dev($sod) 2 0 2
792 # otherwise try looking for devices
793 0 my %dev2s = map {$self->dev($_) => $_} $self->service_names;
794 0 return $dev2s{$sod};
795 }
796  
797 =head2 $bal->forward($incoming_port,$destination_host,@protocols)
798  
799 This method emits appropriate port/host forwarding rules using DNAT
800 address translation. The destination host can be specified using
801 either of these forms:
802  
803 192.168.100.1 # forward to same port as incoming
804 192.168.100.1:8080 # forward to a different port on host
805  
806 Protocols are one or more of 'tcp','udp'. If omitted defaults to tcp.
807  
808 Examples:
809
810 $bal->forward(80 => '192.168.100.1');
811 $bal->forward(80 => '192.168.100.1:8080','tcp');
812  
813 =cut
814  
815 sub forward {
816 3 ▶ my $self = shift;
Subroutine forward: called CC=8 SCAR=20.9
Pod documented
817 3 my ($port,$host,@protocols) = @_;
818 3 ▶ @protocols = ('tcp') unless @protocols;
Branch: 1 branch
BranchTrueFalseTotal
unless @protocols 2 1 3
819  
820 3 my ($dhost,$dport) = split ':',$host;
821 3 ▶ $dhost ||= $host;
Condition33%1/3
$dhost ||= $host
l!l&&r!l&&!r
300
MC/DC0%0/2
$dhost ||= $host
$dhost $host
Truth table33%1/3
A ||= B
A= $dhostB= $host
ABresult
1X1
011
000
822 3 ▶ $dport ||= $port;
Condition66%2/3
$dport ||= $port
l!l&&r!l&&!r
210
MC/DC0%0/2
$dport ||= $port
$dport $port
Truth table66%2/3
A ||= B
A= $dportB= $port
ABresult
1X1
011
000
823  
824 3 my @dev = map {$self->dev($_)} $self->isp_services;
825  
826 3 for my $dev (@dev) {
827 6 for my $protocol (@protocols) {
828 8 $self->iptables("-t nat -A PREROUTING -i $dev -p $protocol --dport $port -j DNAT --to-destination $host");
829 8 for my $lan ($self->lan_services) {
830 32 my $landev = $self->dev($lan);
831 32 my $lannet = $self->net($lan);
832 32 my $lanip = $self->ip($lan);
833 32 ▶ my $syn = $protocol eq 'tcp' ? '--syn' : '';
Branch: 1 branch
BranchTrueFalseTotal
$protocol eq 'tcp' ? : 24 8 32
834 32 $self->iptables("-A FORWARD -p $protocol -o $landev $syn -d $dhost --dport $dport -j ACCEPT");
835 }
836 }
837 }
838 }
839  
840 =head2 $bal->forward_with_snat($incoming_port,$destination_host,@protocols)
841  
842 This method is the same as forward(), except that it also does source
843 NATing from LAN-based requests to make the request appear to have come
844 from the router. This is used when you expose a server, such as a web
845 server, to the internet, but you also need to access the server from
846 machines on the LAN. Use this if you find that the service is visible
847 from outside the LAN but not inside the LAN.
848  
849 Examples:
850  
851 $bal->forward_with_snat(80 => '192.168.100.1');
852 $bal->forward_with_snat(80 => '192.168.100.1:8080','tcp');
853  
854  
855 =cut
856  
857 sub forward_with_snat {
858 0 ▶ my $self = shift;
Subroutine forward_with_snat: not called CC=7 SCAR=40.3
Pod documented
859 0 my ($port,$host,@protocols) = @_;
860  
861 0 ▶ @protocols = ('tcp') unless @protocols;
Branch: 1 branch
BranchTrueFalseTotal
unless @protocols 0 0 0
862  
863 0 my ($dhost,$dport) = split ':',$host;
864 0 ▶ $dhost ||= $host;
Condition0%0/3
$dhost ||= $host
l!l&&r!l&&!r
000
MC/DC0%0/2
$dhost ||= $host
$dhost $host
Truth table0%0/3
A ||= B
A= $dhostB= $host
ABresult
1X1
011
000
865 0 ▶ $dport ||= $port;
Condition0%0/3
$dport ||= $port
l!l&&r!l&&!r
000
MC/DC0%0/2
$dport ||= $port
$dport $port
Truth table0%0/3
A ||= B
A= $dportB= $port
ABresult
1X1
011
000
866  
867 0 for my $protocol (@protocols) {
868 0 for my $svc ($self->isp_services) {
869 0 my $external_ip = $self->ip($svc);
870 0 $self->iptables("-t nat -A PREROUTING -d $external_ip -p $protocol --dport $port -j DNAT --to-destination $host");
871 }
872  
873 0 for my $lan ($self->lan_services) {
874 0 my $lannet = $self->net($lan);
875 0 $self->iptables("-t nat -A POSTROUTING -s $lannet -p $protocol --dport $port -d $host -j MASQUERADE");
876 }
877  
878 0 $self->iptables("-A FORWARD -p $protocol --dport $port -d $host -j ACCEPT");
879  
880 }
881  
882 }
883  
884 =head2 $bal->ip_route(@args)
885  
886 Shortcut for $bal->sh('ip route',@args);
887  
888 =cut
889  
890 27 ▶sub ip_route {shift->sh('ip','route',@_)}
Subroutine ip_route: called CC=1 SCAR=0.0
Pod documented
891  
892 =head2 $bal->ip_rule(@args)
893  
894 Shortcut for $bal->sh('ip rule',@args);
895  
896 =cut
897  
898 4 ▶sub ip_rule {shift->sh('ip','rule',@_)}
Subroutine ip_rule: called CC=1 SCAR=0.0
Pod documented
899  
900 =head2 $verbose = $bal->iptables_verbose([boolean])
901  
902 Makes iptables send an incredible amount of debugging information to
903 syslog.
904  
905 =cut
906  
907 sub iptables_verbose {
908 0 ▶ my $self = shift;
Subroutine iptables_verbose: not called CC=2 SCAR=17.9
Pod documented
909 0 my $d = $self->{iptables_verbose};
910 0 ▶ $self->{iptables_verbose} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
911 0 $d;
912 }
913  
914 =head1 QUERYING THE CONFIGURATION
915  
916 These methods allow you to get information about the Net::ISP::Balance
917 object's configuration, including settings and other characteristics
918 of the various network interfaces.
919  
920 =head2 @names = $bal->service_names
921  
922 Return the list of service names defined in balance.conf.
923  
924 =cut
925  
926 sub service_names {
927 38 ▶ my $self = shift;
Subroutine service_names: called CC=1 SCAR=0.0
Pod documented
928 38 my $s = $self->services;
929 38 return sort keys %$s;
930 }
931  
932 =head2 @names = $bal->isp_services
933  
934 Return list of service names that correspond to load-balanced ISPs.
935  
936 =cut
937  
938 sub isp_services {
939 18 ▶ my $self = shift;
Subroutine isp_services: called CC=1 SCAR=0.0
Pod documented
940 18 my @n = $self->service_names;
941 18 return grep {$self->role($_) eq 'isp'} @n;
942 }
943  
944 =head2 @names = $bal->lan_services
945  
946 Return list of service names that correspond to lans.
947  
948  
949 =cut
950  
951 sub lan_services {
952 17 ▶ my $self = shift;
Subroutine lan_services: called CC=1 SCAR=0.0
Pod documented
953 17 my @n = $self->service_names;
954 17 return grep {$self->role($_) eq 'lan'} @n;
955 }
956  
957 =head2 $state = $bal->event($service => $new_state)
958  
959 Record a transition between "up" and "down" for a named service. The
960 first argument is the name of the ISP service that has changed,
961 e.g. "CABLE". The second argument is either "up" or "down".
962  
963 The method returns a hashref in which the keys are the ISP service names
964 and the values are one of 'up' or 'down'.
965  
966 The persistent state information is stored in /var/lib/lsm/ under a
967 series of files named <SERVICE_NAME>.state.
968  
969 =cut
970  
971 sub event {
972 0 ▶ my $self = shift;
Subroutine event: not called CC=8 SCAR=42.8
Pod documented
973  
974 0 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
975 0 my ($svc,$new_state) = @_;
976 0 ▶ $new_state =~ /^(up|down)$/ or croak "state must be 'up' or down'";
Branch: 1 branch
BranchTrueFalseTotal
$new_state =~ /^(up|down)$/ or croak("state must be 'up' or down'") 0 0 0
977 0 ▶ $self->dev($svc) or croak "service '$svc' is unknown";
Branch: 1 branch
BranchTrueFalseTotal
$self->dev($svc) or croak("service '${svc}' is unknown") 0 0 0
978 0 my $file = "/var/lib/lsm/${svc}.state";
979 0 ▶ my $mode = -e $file ? '+<' : '>';
Branch: 1 branch
BranchTrueFalseTotal
-e $file ? : 0 0 0
980 0 ▶ open my $fh,$mode,$file or croak "Couldn't open $file mode $mode: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, $mode, $file or croak("Couldn't open $file mode ${mode}: $!") 0 0 0
981 0 flock $fh,LOCK_EX;
982 0 truncate $fh,0;
983 0 seek($fh,0,0);
984 0 print $fh $new_state;
985 0 close $fh;
986 }
987  
988 0 my %state;
989 0 for my $svc ($self->isp_services) {
990 0 my $file = "/var/lib/lsm/${svc}.state";
991 0 ▶ if (open my $fh,'<',$file) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, '<', $file) { } 0 0 0
992 0 flock $fh,LOCK_SH;
993 0 my $state = <$fh>;
994 0 close $fh;
995 0 $state{$svc}=$state;
996 } else {
997 0 $state{$svc}='unknown';
998 }
999 }
1000 0 my @up = grep {$state{$_} eq 'up'} keys %state;
1001 0 $self->up(@up);
1002 0 return \%state;
1003 }
1004  
1005 =head2 $bal->run_eventd(@args)
1006  
1007 Runs scripts in response to lsm events. The scripts are stored in
1008 directories named after the events, e.g.:
1009  
1010 /etc/network/lsm/up.d/*
1011 /etc/network/lsm/down.d/*
1012 /etc/network/lsm/long_down.d/*
1013  
1014 Scripts are called with the following arguments:
1015  
1016 0. STATE
1017 1. SERVICE NAME
1018 2. CHECKIP
1019 3. DEVICE
1020 4. WARN_EMAIL
1021 5. REPLIED
1022 6. WAITING
1023 7. TIMEOUT
1024 8. REPLY_LATE
1025 9. CONS_RCVD
1026 10. CONS_WAIT
1027 11. CONS_MISS
1028 12. AVG_RTT
1029 13. SRCIP
1030 14. PREVSTATE
1031 15. TIMESTAMP
1032  
1033 =cut
1034  
1035 sub run_eventd {
1036 0 ▶ my $self = shift;
Subroutine run_eventd: not called CC=6 SCAR=37.4
Pod documented
1037 0 my @args = @_;
1038 0 my $state = $args[0];
1039 0 my $dir = $self->lsm_scripts_dir();
1040 0 my $dird = "$dir/${state}.d";
1041 0 my @files = sort glob("$dird/*");
1042 0 for my $script (sort @files) {
1043 0 ▶ next if $script =~ /^#/;
Branch: 1 branch
BranchTrueFalseTotal
if $script =~ /^#/ 0 0 0
1044 0 ▶ next if $script =~ /~$/;
Branch: 1 branch
BranchTrueFalseTotal
if $script =~ /~$/ 0 0 0
1045 0 ▶ next unless -f $script && -x _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $script and -x _ 0 0 0
Condition0%0/3
-f $script and -x _
!ll&&!rl&&r
000
MC/DC0%0/2
-f $script and -x _
-f $script -x _
Truth table0%0/3
A and B
A= -f $scriptB= -x _
ABresult
0X0
100
111
1046 0 system $script,@args;
1047 }
1048 }
1049  
1050 =head2 @up = $bal->up(@up_services)
1051  
1052 Get or set the list of ISP interfaces that are currently active and
1053 should be used for balancing.
1054  
1055 =cut
1056  
1057 sub up {
1058 5 ▶ my $self = shift;
Subroutine up: called CC=3 SCAR=11.0
Pod documented
1059 5 ▶ $self->{up} = \@_ if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 2 3 5
1060 5 ▶ unless ($self->{up}) { # initialize with running services
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"up"}) 1 4 5
1061 1 my @svc = grep {$self->running($_)} $self->isp_services;
1062 1 $self->{up} = \@svc;
1063 }
1064 5 my @up = @{$self->{up}};
1065 5 return @up;
1066 }
1067  
1068 =head2 $services = $bal->services
1069  
1070 Return a hash containing the configuration information for each
1071 service. The keys are the service names. Here's an example:
1072  
1073 {
1074 0 HASH(0x91201e8)
1075 'CABLE' => HASH(0x9170500)
1076 'dev' => 'eth0'
1077 'fwmark' => 2
1078 'gw' => '191.3.88.1'
1079 'ip' => '191.3.88.152'
1080 'net' => '191.3.88.128/27'
1081 'ping' => 'www.google.ca'
1082 'role' => 'isp'
1083 'running' => 1
1084 'table' => 2
1085 'DSL' => HASH(0x9113e00)
1086 'dev' => 'ppp0'
1087 'fwmark' => 1
1088 'gw' => '112.211.154.198'
1089 'ip' => '11.120.199.108'
1090 'net' => '112.211.154.198/32'
1091 'ping' => 'www.google.ca'
1092 'role' => 'isp'
1093 'running' => 1
1094 'table' => 1
1095 'LAN' => HASH(0x913ce58)
1096 'dev' => 'eth1'
1097 'fwmark' => undef
1098 'gw' => '192.168.10.1'
1099 'ip' => '192.168.10.1'
1100 'net' => '192.168.10.0/24'
1101 'ping' => ''
1102 'role' => 'lan'
1103 'running' => 1
1104 }
1105  
1106 =cut
1107  
1108 39 ▶sub services { return shift->{services} }
Subroutine services: called CC=1 SCAR=0.0
Pod documented
1109  
1110 =head2 $service = $bal->service('CABLE')
1111  
1112 Return the subhash describing the single named service (see services()
1113 above).
1114  
1115 =cut
1116  
1117 sub service {
1118 0 ▶ shift->{services}{shift()};
Subroutine service: not called CC=1 SCAR=6.9
Pod documented
1119 }
1120  
1121 =head2 $dev = $bal->dev('CABLE')
1122  
1123 =head2 $ip = $bal->ip('CABLE')
1124  
1125 =head2 $gateway = $bal->gw('CABLE')
1126  
1127 =head2 $network = $bal->net('CABLE')
1128  
1129 =head2 $role = $bal->role('CABLE')
1130  
1131 =head2 $running = $bal->running('CABLE')
1132  
1133 =head2 $mark_number = $bal->fwmark('CABLE')
1134  
1135 =head2 $routing_table_number = $bal->table('CABLE')
1136  
1137 =head2 $ping_dest = $bal->ping('CABLE')
1138  
1139 These methods pull out the named information from the configuration
1140 data. fwmark() returns a small integer that will be used for marking
1141 connections for routing through one of the ISP connections when an
1142 outgoing connection originates on the LAN and is routed through the
1143 router. table() returns a small integer corresponding to a routing
1144 table used to route connections originating on the router itself.
1145  
1146 =cut
1147  
1148 132 ▶sub dev { shift->_service_field(shift,'dev') }
Subroutine dev: called CC=1 SCAR=0.0
Pod documented
1149 57 ▶sub ip { shift->_service_field(shift,'ip') }
Subroutine ip: called CC=1 SCAR=0.0
Pod documented
1150 4 ▶sub gw { shift->_service_field(shift,'gw') }
Subroutine gw: called CC=1 SCAR=0.0
Pod documented
1151 109 ▶sub net { shift->_service_field(shift,'net') }
Subroutine net: called CC=1 SCAR=0.0
Pod documented
1152 2 ▶sub running { shift->_service_field(shift,'running') }
Subroutine running: called CC=1 SCAR=0.0
Pod documented
1153 247 ▶sub role { shift->_service_field(shift,'role') }
Subroutine role: called CC=1 SCAR=0.0
Pod documented
1154 6 ▶sub fwmark { shift->_service_field(shift,'fwmark') }
Subroutine fwmark: called CC=1 SCAR=0.0
Pod documented
1155 22 ▶sub table { shift->_service_field(shift,'table') }
Subroutine table: called CC=1 SCAR=0.0
Pod documented
1156 2 ▶sub ping { shift->_service_field(shift,'ping') }
Subroutine ping: called CC=1 SCAR=0.0
Pod documented
1157 10 ▶sub weight { shift->_service_field(shift,'weight') }
Subroutine weight: called CC=1 SCAR=0.0
Pod undocumented
1158  
1159 sub _service_field {
1160 591 ▶ my $self = shift;
Subroutine _service_field: called CC=2 SCAR=7.0
1161 591 my ($service,$field) = @_;
1162 591 ▶ my $s = $self->{services}{$service} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $self->{"services"}{$service} or return 0 591 591
1163 591 $s->{$field};
1164 }
1165  
1166 sub _save_custom_chains {
1167 0 ▶ my $self = shift;
Subroutine _save_custom_chains: not called CC=4 SCAR=30.0
1168 0 for my $table ('filter','nat','mangle') {
1169 0 my @rules = split("\n",`sudo iptables -t $table -S`);
1170 # find custom chains
1171 0 my $mine = 'MARK-|REJECTPERM|DROPGEN|DROPINVAL|DROPPERM|DROPSPOOF|DROPFLOOD|DEBUG';
1172 0 ▶ my @chains = grep {!/^-N ($mine)/} grep {/^-N (\S+)/} @rules or next;
Branch: 1 branch
BranchTrueFalseTotal
my(@chains) = grep({not /^-N ($mine)/;} grep({/^-N (\S+)/;} @rules)) or next 0 0 0
1173 0 s/^-N // foreach @chains;
1174 0 my $chains = join '|',map {quotemeta($_)} @chains;
1175 0 my @targets = grep {/-(?:j|A|I) (?:$chains)/} @rules;
1176 0 $self->{_custom_chains}{$table} = [(map {"-N $_"} @chains),@targets];
1177 }
1178 }
1179  
1180 sub _restore_custom_chains {
1181 0 ▶ my $self = shift;
Subroutine _restore_custom_chains: not called CC=4 SCAR=30.0
1182 0 ▶ my $custom_chains = $self->{_custom_chains} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $custom_chains = $self->{"_custom_chains"} or return 0 0 0
1183 0 for my $table (keys %{$custom_chains}) {
1184 0 ▶ my @rules = @{$custom_chains->{$table}} or next;
Branch: 1 branch
BranchTrueFalseTotal
my(@rules) = @{$custom_chains->{$table};} or next 0 0 0
1185 0 $self->iptables([map {"-t $table $_"} @rules]);
1186 }
1187 }
1188  
1189 =head1 FILES AND PATHS
1190  
1191 These are methods that determine where Net::ISP::Balance finds its
1192 configuration files.
1193  
1194 =head2 $path = Net::ISP::Balance->install_etc
1195  
1196 Returns the path to where the network configuration files reside on
1197 this system, e.g. /etc/network. Note that this only knows about
1198 Ubuntu/Debian-style network configuration files in /etc/network, and
1199 RedHat/CentOS network configuration files in
1200 /etc/sysconfig/network-scripts.
1201  
1202 =cut
1203  
1204 sub install_etc {
1205 12 ▶ my $self = shift;
Subroutine install_etc: called CC=3 SCAR=11.4
Pod documented
1206 12 ▶ return '/etc/network' if -d '/etc/network';
Branch: 1 branch
BranchTrueFalseTotal
if -d "/etc/network" 0 12 12
1207 12 ▶ return '/etc/sysconfig/network-scripts' if -d '/etc/sysconfig/network-scripts';
Branch: 1 branch
BranchTrueFalseTotal
if -d "/etc/sysconfig/network-scripts" 0 12 12
1208 12 return '/etc';
1209 }
1210  
1211 =head2 $file = Net::ISP::Balance->default_conf_file
1212  
1213 Returns the path to the default configuration file,
1214 $ETC_NETWORK/balance.conf.
1215  
1216 =cut
1217  
1218 sub default_conf_file {
1219 0 ▶ my $self = shift;
Subroutine default_conf_file: not called CC=1 SCAR=6.9
Pod documented
1220 0 return $self->install_etc.'/balance.conf';
1221 }
1222  
1223 =head2 $dir = Net::ISP::Balance->default_rules_directory
1224  
1225 Returns the path to the directory where the additional router and
1226 firewall rules are stored. On Ubuntu-Debian-derived systems, this is
1227 /etc/network/balance/. On RedHat/CentOS systems, this is
1228 /etc/sysconfig/network-scripts/balance/.
1229  
1230 =cut
1231  
1232 sub default_rules_directory {
1233 1 ▶ my $self = shift;
Subroutine default_rules_directory: called CC=1 SCAR=0.0
Pod documented
1234 1 return $self->install_etc."/balance";
1235 }
1236  
1237 =head2 $file = Net::ISP::Balance->default_lsm_conf_file
1238  
1239 Returns the path to the place where we should store lsm.conf, the file
1240 used to configure the lsm (link status monitor) application.
1241  
1242 On Ubuntu/Debian-derived systems, this will be the file
1243 /etc/network/lsm.conf. On RedHad/CentOS-derived systems, this will be
1244 /etc/sysconfig/network-scripts/lsm.conf.
1245  
1246 =cut
1247  
1248 sub default_lsm_conf_file {
1249 1 ▶ my $self = shift;
Subroutine default_lsm_conf_file: called CC=1 SCAR=0.0
Pod documented
1250 1 return $self->install_etc."/balance/lsm.conf";
1251 }
1252  
1253 =head2 $dir = Net::ISP::Balance->default_lsm_scripts_dir
1254  
1255 Returns the path to the place where lsm stores its helper scripts. On
1256 Ubuntu/Debian-derived systems, this will be the directory
1257 /etc/network/lsm/. On RedHad/CentOS-derived systems, this will be
1258 /etc/sysconfig/network-scripts/lsm/.
1259  
1260 =cut
1261  
1262 sub default_lsm_scripts_dir {
1263 1 ▶ my $self = shift;
Subroutine default_lsm_scripts_dir: called CC=1 SCAR=0.0
Pod documented
1264 1 return $self->install_etc.'/balance/lsm';
1265 }
1266  
1267 =head2 $file = $bal->bal_conf_file([$new_file])
1268  
1269 Get/set the main configuration file path, balance.conf.
1270  
1271 =cut
1272  
1273 sub bal_conf_file {
1274 0 ▶ my $self = shift;
Subroutine bal_conf_file: not called CC=2 SCAR=17.9
Pod documented
1275 0 my $d = $self->{bal_conf_file};
1276 0 ▶ $self->{bal_conf_file} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
1277 0 $d;
1278 }
1279  
1280 =head2 $dir = $bal->rules_directory([$new_rules_directory])
1281  
1282 Get/set the route and firewall rules directory.
1283  
1284 =cut
1285  
1286 sub rules_directory {
1287 3 ▶ my $self = shift;
Subroutine rules_directory: called CC=2 SCAR=6.9
Pod documented
1288 3 my $d = $self->{rules_directory};
1289 3 ▶ $self->{rules_directory} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 2 3
1290 3 $d;
1291 }
1292  
1293 =head2 $file = $bal->lsm_conf_file([$new_conffile])
1294  
1295 Get/set the path to the lsm configuration file.
1296  
1297 =cut
1298  
1299 sub lsm_conf_file {
1300 0 ▶ my $self = shift;
Subroutine lsm_conf_file: not called CC=2 SCAR=17.9
Pod documented
1301 0 my $d = $self->{lsm_conf_file};
1302 0 ▶ $self->{lsm_conf_file} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
1303 0 $d;
1304 }
1305  
1306 =head2 $dir = $bal->lsm_scripts_dir([$new_dir])
1307  
1308 Get/set the path to the lsm scripts directory.
1309  
1310 =cut
1311  
1312 sub lsm_scripts_dir {
1313 1 ▶ my $self = shift;
Subroutine lsm_scripts_dir: called CC=2 SCAR=7.0
Pod documented
1314 1 my $d = $self->{lsm_scripts_dir};
1315 1 ▶ $self->{lsm_scripts_dir} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 1 1
1316 1 $d;
1317 }
1318  
1319 =head1 INFREQUENTLY-USED METHODS
1320  
1321 These are methods that are used internally, but may be useful to
1322 applications developers.
1323  
1324 =head2 $lsm_config_text = $bal->lsm_config_file(-warn_email=>'root@localhost')
1325  
1326 This method creates the text used to create the lsm.conf configuration
1327 file. Pass it a series of -name=>value pairs to incorporate into the
1328 file.
1329  
1330 Possible switches and their defaults are:
1331  
1332 -checkip 127.0.0.1
1333 -eventscript /etc/network/load_balance.pl
1334 -long_down_eventscript /etc/network/load_balance.pl
1335 -notifyscript /etc/network/balance/lsm/default_script
1336 -max_packet_loss 15
1337 -max_successive_pkts_lost 7
1338 -min_packet_loss 5
1339 -min_successive_pkts_rcvd 10
1340 -interval_ms 1000
1341 -timeout_ms 1000
1342 -warn_email root
1343 -check_arp 0
1344 -sourceip <autodiscovered>
1345 -device <autodiscovered> -eventscript => $balance_script,
1346 -ttl 0 <use system value>
1347 -status 2 <no assumptions>
1348 -debug 8 <moderate verbosity from scale of 0 to 100>
1349  
1350 =cut
1351  
1352 sub lsm_config_text {
1353 1 ▶ my $self = shift;
Subroutine lsm_config_text: called CC=4 SCAR=13.9
Pod undocumented
1354 1 my %args = @_;
1355 1 my $scripts_dir = $self->lsm_scripts_dir;
1356 1 my $balance_script = $self->install_etc."/load_balance.pl";
1357 1 my %defaults = (
1358 -checkip => '127.0.0.1',
1359 -debug => 8,
1360 -eventscript => $balance_script,
1361 -long_down_eventscript => $balance_script,
1362 -notifyscript => "$scripts_dir/default_script",
1363 -max_packet_loss => 15,
1364 -max_successive_pkts_lost => 7,
1365 -min_packet_loss => 5,
1366 -min_successive_pkts_rcvd => 10,
1367 -interval_ms => 1000,
1368 -timeout_ms => 1000,
1369 -long_down_time => 120,
1370 -warn_email => 'root',
1371 -check_arp => 0,
1372 -sourceip => undef,
1373 -device => undef,
1374 -ttl => 0,
1375 -status => 2
1376 );
1377 1 %defaults = (%defaults,%{$self->{lsm_config}},%args); # %args supersedes what's in %defaults
1378  
1379 1 my $result = "# This file is autogenerated by load_balancer.pl when it first runs.\n";
1380 1 $result .= "# Do not edit directly. Instead edit /etc/network/balance.conf.\n\n";
1381 1 $result .= "debug=$defaults{-debug}\n\n";
1382 1 delete $defaults{-debug};
1383  
1384 1 $result .= "defaults {\n";
1385 1 $result .= " name=defaults\n";
1386 1 for my $option (sort keys %defaults) {
1387 17 (my $o = $option) =~ s/^-//;
1388 17 ▶ $defaults{$option} = '' unless defined $defaults{$option}; # avoid uninit var warnings
Branch: 1 branch
BranchTrueFalseTotal
unless defined $defaults{$option} 2 15 17
1389 17 $result .= " $o=$defaults{$option}\n";
1390 }
1391 1 $result .= "}\n\n";
1392  
1393 1 for my $svc ($self->isp_services) {
1394 2 my $device = $self->dev($svc);
1395 2 my $src_ip = $self->ip($svc);
1396 2 my $ping = $self->ping($svc);
1397 2 $result .= "connection {\n";
1398 2 $result .= " name=$svc\n";
1399 2 $result .= " device=$device\n";
1400 2 $result .= " checkip=$ping\n";
1401 2 $result .= "}\n\n";
1402 }
1403  
1404 1 return $result;
1405 }
1406  
1407 sub _parse_configuration_file {
1408 1 ▶ my $self = shift;
Subroutine _parse_configuration_file: called CC=13 SCAR=28.5
1409 1 my $path = shift;
1410 1 my (%services,%lsm_options,@forwarding_group);
1411 1 ▶ open my $f,$path or die "Could not open $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $f, $path or die "Could not open ${path}: $!" 0 1 1
1412  
1413 1 ▶ while (<$f>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $f)) 14 1 15
1414 14 chomp;
1415 14 ▶ next if /^\s*#/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\s*#/ 3 11 14
1416 11 ▶ if (/^forwarding_group\s*=\s*(.+)$/) { # routing group
Branch: 1 branch
BranchTrueFalseTotal
if (/^forwarding_group\s*=\s*(.+)$/) 0 11 11
1417 0 ▶ my @group = split /\s+/,$1 or next;
Branch: 1 branch
BranchTrueFalseTotal
my @group = split(/\s+/, $1, 0) or next 0 0 0
1418 0 push @forwarding_group,\@group;
1419 0 next;
1420 }
1421 11 ▶ if (/^(\w+)\s*=\s*(.*)$/) { # lsm config
Branch: 1 branch
BranchTrueFalseTotal
if (/^(\w+)\s*=\s*(.*)$/) 0 11 11
1422 0 $lsm_options{"-${1}"} = $2;
1423 0 next;
1424 }
1425 11 my ($service,$device,$role,$ping_dest,$weight) = split /\s+/;
1426 11 ▶ next unless $service && $device && $role;
Branch: 1 branch
BranchTrueFalseTotal
unless $service and $device and $role 0 7 7
Condition66%4/6
$service and $device and $role
!ll&&!rl&&r
407
$service and $device
!ll&&!rl&&r
407
MC/DC33%1/3
$service and $device and $role
$service $device $role
Truth table50%2/4
A and B and C
A= $serviceB= $deviceC= $role
ABCresult
0XX0
10X0
1100
1111
1427 7 ▶ croak "load_balance.conf line $.: A service can not be named 'up' or 'down'"
Branch: 1 branch
BranchTrueFalseTotal
if $service =~ /^(up|down)$/ 0 7 7
1428 if $service=~/^(up|down)$/;
1429 7 $services{$service}{dev} = $device;
1430 7 $services{$service}{role} = $role;
1431 7 ▶ $services{$service}{ping} = $ping_dest || 'www.google.ca';
Condition100%2/2
$ping_dest || 'www.google.ca'
l!l
34
MC/DC100%1/1
$ping_dest || 'www.google.ca'
$ping_dest
Truth table100%2/2
A
A= $ping_dest
Aresult
11
00
1432 7 ▶ $services{$service}{weight}= $weight || 1;
Condition50%1/2
$weight || 1
l!l
07
MC/DC0%0/1
$weight || 1
$weight
Truth table50%1/2
A
A= $weight
Aresult
11
00
1433 }
1434 1 close $f;
1435 1 $self->{svc_config} = \%services;
1436 1 $self->{lsm_config} = \%lsm_options;
1437 1 $self->{forwarding_groups} = \@forwarding_group;
1438 }
1439  
1440 sub _collect_interfaces_retry {
1441 0 ▶ my $self = shift;
Subroutine _collect_interfaces_retry: not called CC=3 SCAR=24.8
1442 0 my $retries = $self->dev_lookup_retries;
1443 0 my $wait = $self->dev_lookup_retry_delay;
1444 0 my %ifs;
1445 0 for (1..$retries) {
1446 0 delete $self->{_interface_info_cache}; # don't want to cache partial results
1447 0 ▶ last if $self->_collect_interfaces(\%ifs);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_collect_interfaces(\%ifs) 0 0 0
1448 0 sleep $wait;
1449 }
1450 0 $self->{services} = \%ifs;
1451 }
1452  
1453 sub _collect_interfaces {
1454 1 ▶ my $self = shift;
Subroutine _collect_interfaces: called CC=7 SCAR=19.5
1455 1 my $interface_info = shift;
1456  
1457 1 ▶ my $s = $self->{svc_config} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $self->{"svc_config"} or return 0 1 1
1458 1 my $i = $self->interface_info;
1459  
1460 # print STDERR Dumper($i);
1461  
1462 # map devices to services
1463 1 my %devs;
1464 1 for my $svc (keys %$s) {
1465 7 my $vdev = $s->{$svc}{dev};
1466 7 $devs{$vdev}=$svc;
1467 }
1468  
1469 1 my $counter = 0;
1470 1 my $configured_interfaces = 0;
1471  
1472 1 for my $vdev (sort keys %devs) {
1473 7 ▶ my $info = $i->{$vdev} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $info = $i->{$vdev} or next 1 6 7
1474 6 my $dev = $info->{dev};
1475 6 my $svc = $devs{$vdev};
1476 6 my $role = $s->{$svc}{role};
1477 6 $configured_interfaces++;
1478  
1479 # copy into hash passed to us
1480 $interface_info->{$svc} = {
1481 dev => $dev, # otherwise, iptables will croak!!!
1482 running => $info->{running},
1483 gw => $info->{gw},
1484 net => $info->{net},
1485 ip => $info->{ip},
1486 fwmark => $role eq 'isp' ? ++$counter : undef,
1487 table => $role eq 'isp' ? $counter : undef,
1488 role => $role,
1489 ping => $s->{$svc}{ping},
1490 weight => $s->{$svc}{weight},
1491 }
1492 6 ▶ }
Branch: 2 branches
BranchTrueFalseTotal
$role eq 'isp' ? : 2 4 6
$role eq 'isp' ? : 2 4 6
1493 1 return $configured_interfaces >= keys %devs;
1494 }
1495  
1496 =head2 $if_hash = $bal->interface_info
1497  
1498 =head2 $if_hash = Net::ISP::Balance->interface_info
1499  
1500 This method returns a hashref containing information about each of the
1501 network interfaces found on the system (independent of those mentioned
1502 in the configuration file). It may be called as a class method or an
1503 instance method.
1504  
1505 Each key in the hash is the name of a (virtual) interface device. The
1506 values are hashrefs with the following keys:
1507  
1508 key value
1509 --- -----
1510 dev name of the underlying physical device (usually same as vdev)
1511 running boolean, true if interface is running
1512 gw gateway, if present
1513 net subnet in xxx.xxx.xxx.xxx/xx
1514  
1515 =cut
1516  
1517  
1518 sub interface_info {
1519 1 ▶ my $self = shift;
Subroutine interface_info: called CC=21 SCAR=30.9
Pod documented
1520 return $self->{_interface_info_cache}
1521 1 ▶ if ref $self && exists $self->{_interface_info_cache};
Branch: 1 branch
BranchTrueFalseTotal
if ref $self and exists $self->{"_interface_info_cache"} 0 1 1
Condition33%1/3
ref $self and exists $self->{"_interface_info_cache"}
!ll&&!rl&&r
010
MC/DC0%0/2
ref $self and exists $self->{"_interface_info_cache"}
ref $self exists $self->{"_interface_info_cache"}
Truth table33%1/3
A and B
A= ref $selfB= exists $self->{"_interface_info_cache"}
ABresult
0X0
100
111
1522
1523 1 my %results; # keyed by interface device
1524  
1525 # LOGIC TO DEAL WITH VIRTUAL INTERFACES
1526 # 1. From _ip_addr_show get all the inet XXX.XXX.XXX.XXX lines and calculate
1527 # corresponding network and virtual interface.
1528 # 2. Record mapping of network to virtual interface in a hash (%vif)
1529 # 3. When going through the routes, replace $dev with virtual interface name
1530 # 4. In (keys %devs) loop, create an inner loop for each inet found and replace
1531 # device with correct virtual device.
1532  
1533 # get interfaces with assigned addresses
1534 1 my $a = $self->_ip_addr_show;
1535 1 my (undef,@ifs) = split /^\d+: /m,$a;
1536 1 chomp(@ifs);
1537 my %ifs = map {
1538 1 my ($dev,$config) = split(/: /,$_,2);
1539 9 $dev =~ s/\@.+$//; # get rid of bonding master information
1540 9 ($dev,$config);
1541 } @ifs;
1542  
1543 # find virtual interfaces
1544 1 my (%vnet,%vif);
1545 1 for my $dev (keys %ifs) {
1546 9 my $info = $ifs{$dev};
1547 9 ▶ while ($info =~ /inet (\d+\.\d+\.\d+\.\d+)(?:\/(\d+))?.+?(\S+)$/mg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info =~ m[inet (\d+\.\d+\.\d+\.\d+)(?:/(\d+))?.+?(\S+)$]gm) 8 9 17
1548 8 my ($addr,$bits,$vdev) = ($1,$2,$3);
1549 8 ▶ $addr or next;
Branch: 1 branch
BranchTrueFalseTotal
$addr or next 0 8 8
1550 8 ▶ $bits ||= 32;
Condition100%2/2
$bits ||= 32
l!l
62
MC/DC100%1/1
$bits ||= 32
$bits
Truth table100%2/2
A
A= $bits
Aresult
11
00
1551 8 my ($peer) = $info =~ /peer\s+(\d+\.\d+\.\d+\.\d+)/;
1552 8 my $block = Net::Netmask->new2("$addr/$bits");
1553 8 $vnet{$dev}{"$block"} = $vdev;
1554 8 $vif{$dev}{$vdev}{block} = $block;
1555 8 $vif{$dev}{$vdev}{addr} = $addr;
1556 }
1557 }
1558  
1559 # get existing routes
1560 1 my (%gws,%nets);
1561 1 my $r = $self->_ip_route_show;
1562 1 my @routes = split /^(?!\s)/m,$r;
1563 1 chomp(@routes);
1564 1 foreach (@routes) {
1565 8 ▶ while (/(\S+)\s+via\s+(\S+)\s+dev\s+(\S+)/g) {
Branch: 1 branch
BranchTrueFalseTotal
if (/(\S+)\s+via\s+(\S+)\s+dev\s+(\S+)/g) 3 8 11
1566 3 my ($net,$gateway,$dev) = ($1,$2,$3);
1567 3 ▶ ($net) = /^(\S+)/ if $net eq 'nexthop';
Branch: 1 branch
BranchTrueFalseTotal
if $net eq "nexthop" 2 1 3
1568 3 ▶ my $vdev = $vnet{$dev}{$net} || $dev;
Condition33%1/3
$vnet{$dev}{$net} || $dev
l!l&&r!l&&!r
030
MC/DC0%0/2
$vnet{$dev}{$net} || $dev
$vnet{$dev}{$net} $dev
Truth table33%1/3
A || B
A= $vnet{$dev}{$net}B= $dev
ABresult
1X1
011
000
1569 3 ▶ $nets{$vdev} = $net unless $net eq 'default';
Branch: 1 branch
BranchTrueFalseTotal
unless $net eq "default" 1 2 3
1570 3 $gws{$vdev} = $gateway;
1571 }
1572 }
1573 1 for my $dev (keys %ifs) {
1574 9 my $info = $ifs{$dev};
1575 9 my $running = $info =~ /[<,]UP[,>]/;
1576 9 my ($peer) = $info =~ /peer\s+(\d+\.\d+\.\d+\.\d+)/;
1577 9 for my $vdev (keys %{$vif{$dev}}) {
1578 8 my $addr = $vif{$dev}{$vdev}{addr};
1579 8 my $block = $vif{$dev}{$vdev}{block};
1580 8 ▶ my $net = $nets{$dev} || ($peer?"$peer/32":undef) || "$block";
Branch: 1 branch
BranchTrueFalseTotal
$peer ? : 1 6 7
Condition83%5/6
$nets{$dev} || ($peer ? "$peer/32" : undef) || "$block"
l!l&&r!l&&!r
260
$nets{$dev} or $peer ? "$peer/32" : undef
l!l&&r!l&&!r
116
MC/DC0%0/3
$nets{$dev} || ($peer ? "$peer/32" : undef) || "$block"
$nets{$dev} $peer ? "$peer/32" : undef "$block"
Truth table75%3/4
A or B || C
A= $nets{$dev}B= $peer ? "$peer/32" : undefC= "$block"
ABCresult
1XX1
01X1
0011
0000
1581 8 ▶ my $gw = $gws{$dev} || $peer || $self->_dhcp_gateway($dev) || $block->nth(1);
Condition66%6/9
$gws{$dev} || $peer || $self->_dhcp_gateway($dev) || $block->nth(1)
l!l&&r!l&&!r
350
$gws{$dev} or $peer or $self->_dhcp_gateway($dev)
l!l&&r!l&&!r
305
$gws{$dev} or $peer
l!l&&r!l&&!r
305
MC/DC0%0/4
$gws{$dev} || $peer || $self->_dhcp_gateway($dev) || $block->nth(1)
$gws{$dev} $peer $self->_dhcp_gateway($dev) $block->nth(1)
Truth table40%2/5
A or B or C || D
A= $gws{$dev}B= $peerC= $self->_dhcp_gateway($dev)D= $block->nth(1)
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1582  
1583 # copy into hash passed to us
1584 8 $results{$vdev} = {
1585 dev => $dev, # otherwise, iptables will croak!!!
1586 running => $running,
1587 gw => $gw,
1588 net => $net,
1589 ip => $addr,
1590 }
1591 }
1592 }
1593  
1594 1 ▶ $self->{_interface_info_cache} = \%results if ref $self;
Branch: 1 branch
BranchTrueFalseTotal
if ref $self 1 0 1
1595 1 return \%results;
1596 }
1597  
1598 sub _ip_addr_show {
1599 1 ▶ my $self = shift;
Subroutine _ip_addr_show: called CC=2 SCAR=7.6
1600 1 ▶ return eval{$self->{dummy_data}{"ip_addr_show"}} || `ip addr show`;
Condition33%1/3
eval { do { $self->{'dummy_data'}{'ip_addr_show'} } } || `ip addr show`
l!l&&r!l&&!r
100
MC/DC0%0/2
eval { do { $self->{'dummy_data'}{'ip_addr_show'} } } || `ip addr show`
eval { do { $self->{'dummy_data'}{'ip_addr_show'} } } `ip addr show`
Truth table33%1/3
A || B
A= eval { do { $self->{'dummy_data'}{'ip_addr_show'} } }B= `ip addr show`
ABresult
1X1
011
000
1601 }
1602  
1603 sub _ip_route_show {
1604 1 ▶ my $self = shift;
Subroutine _ip_route_show: called CC=2 SCAR=7.6
1605 1 ▶ return eval{$self->{dummy_data}{"ip_route_show"}} || `ip route show all`;
Condition33%1/3
eval { do { $self->{'dummy_data'}{'ip_route_show'} } } || `ip route show all`
l!l&&r!l&&!r
100
MC/DC0%0/2
eval { do { $self->{'dummy_data'}{'ip_route_show'} } } || `ip route show all`
eval { do { $self->{'dummy_data'}{'ip_route_show'} } } `ip route show all`
Truth table33%1/3
A || B
A= eval { do { $self->{'dummy_data'}{'ip_route_show'} } }B= `ip route show all`
ABresult
1X1
011
000
1606 }
1607  
1608 # This subroutine is called for dhcp-assigned IP addresses to try to
1609 # get the gateway. It is used for those unusual cases in which the gateway
1610 # is NOT the first IP address in the net block.
1611 # In versions 1.05 and older, we tried to recover this information on static
1612 # interfaces by reading /etc/network/interfaces as well, but the file location was too
1613 # unpredictable across different Linux distros.
1614 sub _dhcp_gateway {
1615 5 ▶ my $self = shift;
Subroutine _dhcp_gateway: called CC=4 SCAR=22.9
1616 5 my $dev = shift;
1617 5 ▶ my $fh = $self->_open_dhclient_leases($dev) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $fh = $self->_open_dhclient_leases($dev) or return 5 0 5
1618 0 my ($gw);
1619 0 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 0 0 0
1620 0 chomp;
1621 0 ▶ $gw = $1 if /option routers (\S+)[,;]/;
Branch: 1 branch
BranchTrueFalseTotal
if /option routers (\S+)[,;]/ 0 0 0
1622 }
1623 0 return $gw;
1624 }
1625  
1626 sub _open_dhclient_leases {
1627 5 ▶ my $self = shift;
Subroutine _open_dhclient_leases: called CC=5 SCAR=23.1
1628 5 my $device = shift;
1629 5 ▶ if (my $dummy = eval{$self->{dummy_data}{"leases_$device"}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dummy = eval { do { $self->{"dummy_data"}{"leases_$device"} } }) 0 5 5
1630 0 ▶ open my $fh,'<',\$dummy or die $!;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", \$dummy or die $! 0 0 0
1631 0 return $fh;
1632 }
1633 5 ▶ my $leases = $self->_find_dhclient_leases($device) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $leases = $self->_find_dhclient_leases($device) or return 5 0 5
1634 0 ▶ open my $fh,$leases or die "Can't open $leases: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, $leases or die "Can't open ${leases}: $!" 0 0 0
1635 0 return $fh;
1636 }
1637  
1638 sub _find_dhclient_leases {
1639 5 ▶ my $self = shift;
Subroutine _find_dhclient_leases: called CC=3 SCAR=11.2
1640 5 my $device = shift;
1641 5 my @locations = ('/var/lib/NetworkManager','/var/lib/dhcp','/var/lib/dhclient');
1642 5 for my $l (@locations) {
1643 15 my @matches = glob("$l/dhclient*$device.lease*");
1644 15 ▶ next unless @matches;
Branch: 1 branch
BranchTrueFalseTotal
unless @matches 15 0 15
1645 0 return $matches[0];
1646 }
1647 5 return;
1648 }
1649  
1650  
1651  
1652 #################################### here are the routing rules ###################
1653  
1654 =head2 $bal->set_routes()
1655  
1656 This method is called by set_routes_and_firewall() to emit the rules
1657 needed to create the load balancing routing tables.
1658  
1659 =cut
1660  
1661 sub set_routes {
1662 0 ▶ my $self = shift;
Subroutine set_routes: not called CC=1 SCAR=6.9
Pod documented
1663 0 $self->routing_rules();
1664 0 $self->local_routing_rules();
1665 }
1666  
1667 =head2 $bal->set_firewall
1668  
1669 This method is called by set_routes_and_firewall() to emit the rules
1670 needed to create the balancing firewall.
1671  
1672 =cut
1673  
1674 sub set_firewall {
1675 0 ▶ my $self = shift;
Subroutine set_firewall: not called CC=2 SCAR=17.9
Pod documented
1676 0 ▶ if ($self->keep_custom_chains) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->keep_custom_chains) { } 0 0 0
1677 0 $self->_save_custom_chains;
1678 0 $self->base_fw_rules();
1679 0 $self->_restore_custom_chains;
1680 } else {
1681 0 $self->base_fw_rules();
1682 }
1683  
1684 0 $self->balancing_fw_rules();
1685 0 $self->sanity_fw_rules();
1686 0 $self->nat_fw_rules();
1687 0 $self->local_fw_rules();
1688 }
1689  
1690  
1691 =head2 $bal->enable_forwarding($boolean)
1692  
1693 =cut
1694  
1695 sub enable_forwarding {
1696 1 ▶ my $self = shift;
Subroutine enable_forwarding: called CC=2 SCAR=7.1
Pod documented
1697 1 ▶ my $enable = $_[0] ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$_[0] ? : 0 1 1
1698 1 $self->sh("echo $enable > /proc/sys/net/ipv4/ip_forward");
1699 }
1700 =head2 $bal->routing_rules()
1701  
1702 This method is called by set_routes() to emit the rules
1703 needed to create the routing rules.
1704  
1705 =cut
1706  
1707 sub routing_rules {
1708 1 ▶ my $self = shift;
Subroutine routing_rules: called CC=2 SCAR=6.9
Pod undocumented
1709 # main table
1710 1 $self->ip_route("add ",$self->net($_),'dev',$self->dev($_),'src',$self->ip($_)) foreach $self->service_names;
1711 1 $self->_create_default_route();
1712 1 $self->_create_service_routing_tables();
1713 }
1714  
1715 sub _initialize_routes {
1716 0 ▶ my $self = shift;
Subroutine _initialize_routes: not called CC=2 SCAR=17.9
1717 0 $self->sh(<<END);
1718 ip route flush all
1719 ip rule flush
1720 ip rule add from all lookup main pref 32766
1721 ip rule add from all lookup default pref 32767
1722 END
1723 ;
1724  
1725 0 $self->ip_route("flush table ",$self->table($_)) foreach $self->isp_services;
1726 }
1727  
1728 sub _create_default_route {
1729 1 ▶ my $self = shift;
Subroutine _create_default_route: called CC=9 SCAR=25.1
1730 1 my $D = shift;
1731  
1732 1 my @up = $self->up;
1733  
1734 # create multipath route
1735 1 ▶ if (@up > 1) { # multipath
Branch: 1 branch
BranchTrueFalseTotal
if (@up > 1) { } 1 0 1
1736 1 ▶ print STDERR "# setting multipath default gw\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 1 1
1737 # EG
1738 # ip route add default scope global nexthop via 192.168.10.1 dev eth0 weight 1 \
1739 # nexthop via 192.168.11.1 dev eth1 weight 1
1740 1 my $hops = '';
1741 1 for my $svc (@up) {
1742 2 ▶ my $gw = $self->gw($svc) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $gw = $self->gw($svc) or next 0 2 2
1743 2 ▶ my $dev = $self->dev($svc) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $dev = $self->dev($svc) or next 0 2 2
1744 2 ▶ my $weight = $self->weight($svc) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $weight = $self->weight($svc) or next 0 2 2
1745 2 $hops .= "nexthop via $gw dev $dev weight $weight ";
1746 }
1747 1 ▶ die "no valid gateways!" unless $hops;
Branch: 1 branch
BranchTrueFalseTotal
unless $hops 0 1 1
1748 1 $self->ip_route("add default scope global $hops");
1749 }
1750  
1751 else {
1752 0 ▶ print STDERR "# setting single default route via $up[0]n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 0 0
1753 0 $self->ip_route("add default via",$self->gw($up[0]),'dev',$self->dev($up[0]));
1754 }
1755  
1756 }
1757  
1758 sub _create_service_routing_tables {
1759 1 ▶ my $self = shift;
Subroutine _create_service_routing_tables: called CC=4 SCAR=13.9
1760  
1761 1 for my $svc ($self->isp_services) {
1762 2 ▶ print STDERR "# creating routing table for $svc\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 2 2
1763 2 $self->ip_route('add table',$self->table($svc),'default dev',$self->dev($svc),'via',$self->gw($svc));
1764 2 for my $s ($self->service_names) {
1765 14 $self->ip_route('add table',$self->table($svc),$self->net($s),'dev',$self->dev($s),'src',$self->ip($s));
1766 }
1767 2 $self->ip_rule('add from',$self->ip($svc),'table',$self->table($svc));
1768 2 $self->ip_rule('add fwmark',$self->fwmark($svc),'table',$self->table($svc));
1769 }
1770 }
1771  
1772 =head2 $bal->local_routing_rules()
1773  
1774 This method is called by set_routes() to process the fules and emit
1775 the commands contained in the customized route files located in
1776 $ETC_DIR/balance/routes.
1777  
1778 =cut
1779  
1780 sub local_routing_rules {
1781 1 ▶ my $self = shift;
Subroutine local_routing_rules: called CC=1 SCAR=0.0
Pod documented
1782 1 my $dir = $self->rules_directory;
1783 1 my @files = sort glob("$dir/routes/*");
1784 1 $self->_execute_rules_files(@files);
1785 }
1786  
1787 =head2 $bal->local_fw_rules()
1788  
1789 This method is called by set_firewall() to process the fules and emit
1790 the commands contained in the customized route files located in
1791 $ETC_DIR/balance/firewall.
1792  
1793 =cut
1794  
1795 sub local_fw_rules {
1796 1 ▶ my $self = shift;
Subroutine local_fw_rules: called CC=1 SCAR=0.0
Pod documented
1797 1 my $dir = $self->rules_directory;
1798 1 my @files = sort glob("$dir/firewall/*");
1799 1 $self->_execute_rules_files(@files);
1800 }
1801  
1802 =head2 $bal->pre_run_rules()
1803  
1804 This method is called by set_routes_and_firewall() to process the fules and emit
1805 the commands contained in the customized route files located in
1806 $ETC_DIR/balance/pre-run.
1807  
1808 =cut
1809  
1810 sub pre_run_rules {
1811 0 ▶ my $self = shift;
Subroutine pre_run_rules: not called CC=1 SCAR=6.9
Pod documented
1812 0 my $dir = $self->rules_directory;
1813 0 my @files = sort glob("$dir/pre-run/*");
1814 0 $self->_execute_rules_files(@files);
1815 }
1816  
1817 =head2 $bal->post_run_rules()
1818  
1819 This method is called by set__routes_andfirewall() to process the
1820 fules and emit the commands contained in the customized route files
1821 located in $ETC_DIR/balance/post-run.
1822  
1823 =cut
1824  
1825 sub post_run_rules {
1826 0 ▶ my $self = shift;
Subroutine post_run_rules: not called CC=1 SCAR=6.9
Pod documented
1827 0 my $dir = $self->rules_directory;
1828 0 my @files = sort glob("$dir/post-run/*");
1829 0 $self->_execute_rules_files(@files);
1830 }
1831  
1832  
1833 sub _execute_rules_files {
1834 2 ▶ my $self = shift;
Subroutine _execute_rules_files: called CC=11 SCAR=25.2
1835 2 my @files = @_;
1836  
1837 2 for my $f (@files) {
1838 5 ▶ next if $f =~ /~$/; # ignore emacs backup files
Branch: 1 branch
BranchTrueFalseTotal
if $f =~ /~$/ 0 5 5
1839 5 ▶ next if $f =~ /^#/; # ignore autosave files
Branch: 1 branch
BranchTrueFalseTotal
if $f =~ /^#/ 0 5 5
1840 5 ▶ print STDERR "# executing contents of $f\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 5 5
1841 5 $self->sh("## Including rules from $f ##\n");
1842 5 ▶ next if $f =~ /(~|\.bak)$/ or $f=~/^#/;
Branch: 1 branch
BranchTrueFalseTotal
if $f =~ /(~|\.bak)$/ or $f =~ /^#/ 0 5 5
Condition33%1/3
$f =~ /(~|\.bak)$/ or $f =~ /^#/
l!l&&r!l&&!r
005
MC/DC0%0/2
$f =~ /(~|\.bak)$/ or $f =~ /^#/
$f =~ /(~|\.bak)$/ $f =~ /^#/
Truth table33%1/3
A or B
A= $f =~ /(~|\.bak)$/B= $f =~ /^#/
ABresult
1X1
011
000
1843  
1844 5 ▶ if ($f =~ /\.pl$/) { # perl script
Branch: 1 branch
BranchTrueFalseTotal
if ($f =~ /\.pl$/) { } 3 2 5
1845 3 our $B = $self;
1846 3 do $f;
1847 3 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 3 3
1848 } else {
1849 2 ▶ open my $fh,$f or die "Couldn't open $f: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, $f or die "Couldn't open ${f}: $!" 0 2 2
1850 2 ▶ $self->sh($_) while <$fh>;
Branch: 1 branch
BranchTrueFalseTotal
defined($_ = readline $fh) and do { $self->sh($_) } 2 2 4
1851 2 close $fh;
1852 }
1853 5 $self->sh("## Finished $f ##\n");
1854 }
1855 }
1856  
1857 #########################
1858 # firewall rules
1859 #########################
1860  
1861 sub _initialize_firewall {
1862 0 ▶ my $self = shift;
Subroutine _initialize_firewall: not called CC=1 SCAR=6.9
1863 0 $self->sh(<<END);
1864 iptables -F
1865 iptables -X
1866 iptables -t nat -F
1867 iptables -t nat -X
1868 iptables -t mangle -F
1869 iptables -t mangle -X
1870 END
1871 }
1872  
1873 =head2 $bal->base_fw_rules()
1874  
1875 This method is called by set_firewall() to set up basic firewall
1876 rules, including default rules and reporting.
1877  
1878 =cut
1879  
1880 sub base_fw_rules {
1881 0 ▶ my $self = shift;
Subroutine base_fw_rules: not called CC=3 SCAR=24.8
Pod documented
1882 0 $self->sh(<<END);
1883 iptables -P INPUT DROP
1884 iptables -P OUTPUT DROP
1885 iptables -P FORWARD DROP
1886  
1887 iptables -N REJECTPERM
1888 iptables -A REJECTPERM -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "REJECTED: "
1889 iptables -A REJECTPERM -j REJECT --reject-with icmp-net-unreachable
1890  
1891 iptables -N DROPGEN
1892 iptables -A DROPGEN -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "GENERAL: "
1893 iptables -A DROPGEN -j DROP
1894  
1895 iptables -N DROPINVAL
1896 iptables -A DROPINVAL -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "INVALID: "
1897 iptables -A DROPINVAL -j DROP
1898  
1899 iptables -N DROPPERM
1900 iptables -A DROPPERM -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "ACCESS-DENIED: "
1901 iptables -A DROPPERM -j DROP
1902  
1903 iptables -N DROPSPOOF
1904 iptables -A DROPSPOOF -j LOG -m limit --limit 1/minute --log-level 4 --log-prefix "DROP-SPOOF: "
1905 iptables -A DROPSPOOF -j DROP
1906  
1907 iptables -N DROPFLOOD
1908 iptables -A DROPFLOOD -m limit --limit 1/minute -j LOG --log-level 4 --log-prefix "DROP-FLOOD: "
1909 iptables -A DROPFLOOD -j DROP
1910  
1911 iptables -N DEBUG
1912 iptables -A DEBUG -j LOG --log-level 3 --log-prefix "DEBUG: "
1913 END
1914 ;
1915 0 ▶ if ($self->iptables_verbose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->iptables_verbose) 0 0 0
1916 0 ▶ print STDERR " #Setting up debugging logging\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 0 0
1917 0 $self->sh(<<END);
1918 iptables -A INPUT -j LOG --log-prefix "INPUT: "
1919 iptables -A OUTPUT -j LOG --log-prefix "OUTPUT: "
1920 iptables -A FORWARD -j LOG --log-prefix "FORWARD: "
1921 iptables -t nat -A INPUT -j LOG --log-prefix "nat INPUT: "
1922 iptables -t nat -A OUTPUT -j LOG --log-prefix "nat OUTPUT: "
1923 iptables -t nat -A FORWARD -j LOG --log-prefix "nat FORWARD: "
1924 iptables -t nat -A PREROUTING -j LOG --log-prefix "nat PREROUTING: "
1925 iptables -t nat -A POSTROUTING -j LOG --log-prefix "nat POSTROUTING: "
1926 iptables -t mangle -A INPUT -j LOG --log-prefix "mangle INPUT: "
1927 iptables -t mangle -A OUTPUT -j LOG --log-prefix "mangle OUTPUT: "
1928 iptables -t mangle -A FORWARD -j LOG --log-prefix "mangle FORWARD: "
1929 iptables -t mangle -A PREROUTING -j LOG --log-prefix "mangle PRE: "
1930 END
1931 ;
1932 }
1933 }
1934  
1935 =head2 $bal->balancing_fw_rules()
1936  
1937 This method is called by set_firewall() to set up the mangle/fwmark
1938 rules for balancing outgoing connections.
1939  
1940 =cut
1941  
1942 sub balancing_fw_rules {
1943 2 ▶ my $self = shift;
Subroutine balancing_fw_rules: called CC=11 SCAR=24.3
Pod documented
1944  
1945 2 ▶ print STDERR "# balancing FW rules\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 2 2
1946  
1947 2 for my $svc ($self->isp_services) {
1948 4 my $table = $self->mark_table($svc);
1949 4 my $mark = $self->fwmark($svc);
1950 4 ▶ next unless defined $mark && defined $table;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mark and defined $table 0 4 4
Condition33%1/3
defined $mark and defined $table
!ll&&!rl&&r
004
MC/DC0%0/2
defined $mark and defined $table
defined $mark defined $table
Truth table33%1/3
A and B
A= defined $markB= defined $table
ABresult
0X0
100
111
1951 4 $self->sh(<<END);
1952 iptables -t mangle -N $table
1953 iptables -t mangle -A $table -j MARK --set-mark $mark
1954 iptables -t mangle -A $table -j CONNMARK --save-mark
1955 END
1956 }
1957  
1958 2 my @up = $self->up;
1959  
1960 # packets from LAN
1961 2 for my $lan ($self->lan_services) {
1962 8 my $landev = $self->dev($lan);
1963 8 my $src = $self->net($lan);
1964
1965 8 ▶ if (@up > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@up > 1) { } 4 4 8
1966 4 ▶ print STDERR "# creating balanced mangling rules\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 4 4
1967 4 my $count = @up;
1968 4 my $probabilities = $self->_weight_to_probability(\@up);
1969 4 for my $svc (sort {$probabilities->{$b} <=> $probabilities->{$a}} @up) {
1970 8 my $table = $self->mark_table($svc);
1971 8 my $probability = $probabilities->{$svc};
1972 8 $self->iptables("-t mangle -A PREROUTING -i $landev -s $src -m conntrack --ctstate NEW -m statistic --mode random --probability $probability -j $table");
1973 }
1974 }
1975  
1976 else {
1977 4 my $svc = $up[0];
1978 4 ▶ print STDERR "# forcing all traffic through $svc\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 4 4
1979 4 my $table = $self->mark_table($svc);
1980 4 $self->iptables("-t mangle -A PREROUTING -i $landev -s $src -m conntrack --ctstate NEW -j $table");
1981 }
1982  
1983 8 $self->iptables("-t mangle -A PREROUTING -i $landev -s $src -m conntrack --ctstate ESTABLISHED,RELATED -j CONNMARK --restore-mark");
1984 }
1985  
1986 # inbound packets from WAN
1987 2 for my $wan ($self->isp_services) {
1988 4 my $dev = $self->dev($wan);
1989 4 my $table = $self->mark_table($wan);
1990 4 my $src = $self->net($wan);
1991 4 $self->iptables("-t mangle -A PREROUTING -i $dev -m conntrack --ctstate NEW -j $table");
1992 4 $self->iptables("-t mangle -A PREROUTING -i $dev -m conntrack --ctstate ESTABLISHED,RELATED -j CONNMARK --restore-mark");
1993 }
1994  
1995 }
1996  
1997 sub _weight_to_probability {
1998 4 ▶ my $self = shift;
Subroutine _weight_to_probability: called CC=4 SCAR=13.9
1999 4 my $svcs = shift;
2000  
2001 # first turn weights into proportions of the total
2002 4 my %weights = map {$_ => $self->weight($_)} @$svcs;
2003 4 my $total = 0;
2004 4 $total += $_ foreach (values %weights);
2005 4 my %proportions = map {$_ => $weights{$_}/$total} keys %weights;
2006  
2007 # now turn them into probabilities
2008 4 my %probabilities;
2009  
2010 4 my $last = 0;
2011 4 ▶ for (sort {$proportions{$a}<=>$proportions{$b} || $a cmp $b} keys %proportions) {
Branch: 1 branch
BranchTrueFalseTotal
$proportions{$a} <=> $proportions{$b} or $a cmp $b 4 0 4
2012 8 my $threshold = $proportions{$_}/(1-$last);
2013 8 $last += $proportions{$_};
2014 8 $probabilities{$_} = $threshold;
2015 }
2016 4 return \%probabilities;
2017 }
2018  
2019 =head2 $bal->sanity_fw_rules()
2020  
2021 This is called by set_firewall() to create a sensible series of
2022 firewall rules that seeks to prevent spoofing, flooding, and other
2023 antisocial behavior. It also enables UDP-based network time and domain
2024 name service.
2025  
2026 =cut
2027  
2028 sub sanity_fw_rules {
2029 1 ▶ my $self = shift;
Subroutine sanity_fw_rules: called CC=5 SCAR=16.1
Pod documented
2030  
2031 # if any of the devices are ppp, then we clamp the mss
2032 1 my @ppp_devices = grep {/ppp\d+/} map {$self->dev($_)} $self->isp_services;
2033 $self->iptables("-t mangle -A POSTROUTING -o $_ -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu")
2034 1 foreach @ppp_devices;
2035  
2036 # lo is ok
2037 1 $self->iptables(['-A INPUT -i lo -j ACCEPT',
2038 '-A OUTPUT -o lo -j ACCEPT',
2039 '-A INPUT -d 127.0.0.0/8 -j DROPPERM']);
2040  
2041 # accept continuing foreign traffic
2042 1 $self->iptables(['-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT',
2043 '-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT',
2044 '-A INPUT -p tcp --tcp-flags SYN,ACK ACK -j ACCEPT',
2045 '-A FORWARD -p tcp --tcp-flags SYN,ACK ACK -j ACCEPT',
2046 '-A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST RST -j ACCEPT'
2047 ]);
2048  
2049 # we allow ICMP echo, but establish flood limits
2050 1 $self->iptables(['-A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT',
2051 '-A INPUT -p icmp --icmp-type echo-request -j DROPFLOOD']);
2052  
2053 # allowable traffic patterns within the LAN services
2054 1 for my $lan ($self->lan_services) {
2055 4 my $dev = $self->dev($lan);
2056 4 my $net = $self->net($lan);
2057  
2058 # allow unlimited traffic from internal network using legit address
2059 4 $self->iptables("-A INPUT -i $dev -s $net -j ACCEPT");
2060  
2061 # allow locally-generated output to the LAN on the LANDEV
2062 4 $self->iptables("-A OUTPUT -o $dev -d $net -j ACCEPT");
2063  
2064 # and allow broadcasts to the lan
2065 4 $self->iptables("-A OUTPUT -o $dev -d 255.255.255.255/32 -j ACCEPT");
2066  
2067 # any outgoing udp packet is fine with me
2068 4 $self->iptables("-A OUTPUT -p udp -s $net -j ACCEPT");
2069 }
2070  
2071 # allow appropriate outgoing traffic via the ISPs
2072 # NOTE: we use svc_config here so that we allow outgoing traffic
2073 # on interfaces that might be down
2074 # for my $svc ($self->isp_services) {
2075 # my $ispdev = $self->dev($svc);
2076 # $self->iptables("-A OUTPUT -o $ispdev -j ACCEPT");
2077 # }
2078 1 for my $svc (keys %{$self->{svc_config}}) {
2079 7 ▶ next unless $self->{svc_config}{$svc}{role} eq 'isp';
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"svc_config"}{$svc}{"role"} eq "isp" 4 3 7
2080 3 my $ispdev = $self->{svc_config}{$svc}{dev};
2081 3 $self->iptables("-A OUTPUT -o $ispdev -j ACCEPT");
2082 }
2083  
2084 # forwarding rules
2085 1 $self->_lan_wan_forwarding_rules();
2086 1 $self->_lan_lan_forwarding_rules();
2087  
2088 # anything else is bizarre and should be dropped
2089 1 $self->iptables('-A OUTPUT -j DROPSPOOF');
2090 }
2091  
2092 # establish expected traffic patterns between lan(s) and isp interfaces
2093 sub _lan_wan_forwarding_rules {
2094 1 ▶ my $self = shift;
Subroutine _lan_wan_forwarding_rules: called CC=4 SCAR=13.9
2095  
2096 1 for my $lan ($self->lan_services) {
2097 4 my $dev = $self->dev($lan);
2098 4 my $net = $self->net($lan);
2099  
2100 # lan/wan forwarding
2101 # allow lan/wan forwarding
2102 4 for my $svc ($self->isp_services) {
2103 8 my $ispdev = $self->dev($svc);
2104 8 ▶ my $target = $self->_allow_forwarding($lan,$svc) ? 'ACCEPT' : 'REJECTPERM';
Branch: 1 branch
BranchTrueFalseTotal
$self->_allow_forwarding($lan, $svc) ? : 8 0 8
2105 8 $self->iptables("-A FORWARD -i $dev -o $ispdev -s $net -j $target");
2106 }
2107 }
2108 }
2109  
2110 # Allow forwarding between lans
2111 sub _lan_lan_forwarding_rules {
2112 1 ▶ my $self = shift;
Subroutine _lan_lan_forwarding_rules: called CC=5 SCAR=16.1
2113  
2114 # This generates a very long list of rules if you have multiple lan services, but I think
2115 # it is the most general way to get this right.
2116 1 my @lans = $self->lan_services;
2117 1 ▶ for (my $i=0;$i<@lans;$i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @lans) 4 1 5
2118 4 ▶ for (my $j=0;$j<@lans;$j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @lans) 16 4 20
2119 16 ▶ next if $i == $j;
Branch: 1 branch
BranchTrueFalseTotal
if $i == $j 4 12 16
2120 12 my $lan1 = $lans[$i];
2121 12 my $lan2 = $lans[$j];
2122 12 ▶ my $target = $self->_allow_forwarding($lan1,$lan2) ? 'ACCEPT' : 'REJECTPERM';
Branch: 1 branch
BranchTrueFalseTotal
$self->_allow_forwarding($lan1, $lan2) ? : 12 0 12
2123 12 $self->iptables('-A FORWARD','-i',$self->dev($lan1),'-o',$self->dev($lan2),'-s',$self->net($lan1),'-d',$self->net($lan2),"-j $target");
2124 }
2125 }
2126 }
2127  
2128 sub _allow_forwarding {
2129 20 ▶ my $self = shift;
Subroutine _allow_forwarding: called CC=1 SCAR=0.0
2130 20 my ($net_a,$net_b) = @_;
2131 20 my $forward = $self->_forwarding_groups();
2132 20 my $key = join ',',sort ($net_a,$net_b);
2133 20 return $forward->{$key};
2134 }
2135  
2136 # this returns a hashref of service pairs that are allowed to forward packets.
2137 # the keys are service name pairs, in alphabetic order, separated by a comma.
2138 sub _forwarding_groups {
2139 20 ▶ my $self = shift;
Subroutine _forwarding_groups: called CC=8 SCAR=20.8
2140  
2141 # _forwarding_groups is the processed and normalized version of forwarding_groups
2142 20 ▶ return $self->{_forwarding_groups} if exists $self->{_forwarding_groups};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"_forwarding_groups"} 19 1 20
2143  
2144 1 my %allowed_pairs;
2145 1 my $fgs = $self->{forwarding_groups};
2146 1 ▶ unless (@$fgs) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$fgs) 1 0 1
2147 1 $fgs = [[':isp',':lan']];
2148 }
2149  
2150 1 for my $fg (@$fgs) {
2151 my @services = map {
2152 1 ▶ /^:isp$/ ? $self->isp_services
Branch: 2 branches
BranchTrueFalseTotal
/^:isp$/ ? : 1 1 2
/^:lan$/ ? : 1 0 1
2153 : /^:lan$/ ? $self->lan_services
2154 : $_
2155 } @$fg;
2156  
2157 1 ▶ for (my $i=0;$i<@services-1;$i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @services - 1) 5 1 6
2158 5 ▶ for (my $j=$i;$j<@services;$j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @services) 20 5 25
2159 20 my $key = join ',',sort ($services[$i],$services[$j]);
2160 20 $allowed_pairs{$key}++;
2161 }
2162 }
2163 }
2164 1 return $self->{_forwarding_groups} = \%allowed_pairs;
2165 }
2166  
2167 =head2 $bal->nat_fw_rules()
2168  
2169 This is called by set_firewall() to set up basic NAT rules for lan traffic over ISP
2170  
2171 =cut
2172  
2173 sub nat_fw_rules {
2174 0 ▶ my $self = shift;
Subroutine nat_fw_rules: not called CC=3 SCAR=24.8
Pod documented
2175 0 ▶ return unless $self->lan_services;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->lan_services 0 0 0
2176 $self->iptables('-t nat -A POSTROUTING -o',$self->dev($_),'-j MASQUERADE')
2177 0 foreach $self->isp_services;
2178 }
2179  
2180 =head2 $bal->start_lsm()
2181  
2182 Start an lsm process.
2183  
2184 =cut
2185  
2186 sub start_lsm {
2187 0 ▶ my $self = shift;
Subroutine start_lsm: not called CC=1 SCAR=6.9
Pod documented
2188 0 my $lsm = Net::ISP::Balance::ConfigData->config('lsm_path');
2189 0 my $lsm_conf = $self->lsm_conf_file;
2190 0 system "$lsm $lsm_conf /var/run/lsm.pid";
2191 }
2192  
2193 =head2 $bal->signal_lsm($signal)
2194  
2195 Send a signal to a running LSM and return true if successfully
2196 signalled. The signal can be numeric (e.g. 9) or a string ('TERM').
2197  
2198 =cut
2199  
2200 sub signal_lsm {
2201 0 ▶ my $self = shift;
Subroutine signal_lsm: not called CC=4 SCAR=30.0
Pod documented
2202 0 my $signal = shift;
2203 0 ▶ $signal ||= 0;
Condition0%0/2
$signal ||= 0
l!l
00
MC/DC0%0/1
$signal ||= 0
$signal
Truth table0%0/2
A
A= $signal
Aresult
11
00
2204 0 my $pid;
2205 0 ▶ open my $f,'/var/run/lsm.pid' or return;
Branch: 1 branch
BranchTrueFalseTotal
open my $f, "/var/run/lsm.pid" or return 0 0 0
2206 0 chomp($pid = <$f>);
2207 0 close $f;
2208 0 ▶ return unless $pid =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $pid =~ /^\d+$/ 0 0 0
2209 0 return kill($signal=>$pid);
2210 }
2211  
2212  
2213 2 1;
2214  
2215 =head1 BUGS
2216  
2217 Please report bugs to GitHub: https://github.com/lstein/Net-ISP-Balance.
2218  
2219 =head1 AUTHOR
2220  
2221 Copyright 2014, Lincoln D. Stein (lincoln.stein@gmail.com)
2222  
2223 Senior Principal Investigator,
2224 Ontario Institute for Cancer Research
2225  
2226 =head1 LICENSE
2227  
2228 This package is distributed under the terms of the Perl Artistic
2229 License 2.0. See http://www.perlfoundation.org/artistic_license_2_0.
2230  
2231 =cut
2232  
2233 __END__
« blib/lib/Net/ISP/Balance/ConfigData.pm ↑ Summary blib/lib/Net/ISP/Balance.pm »