Project

General

Profile

Download (41.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * gwlb.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2008 Bill Marquette, Seth Mos
7
 * Copyright (c) 2008-2016 Rubicon Communications, LLC (Netgate)
8
 * All rights reserved.
9
 *
10
 * Redistribution and use in source and binary forms, with or without
11
 * modification, are permitted provided that the following conditions are met:
12
 *
13
 * 1. Redistributions of source code must retain the above copyright notice,
14
 *    this list of conditions and the following disclaimer.
15
 *
16
 * 2. Redistributions in binary form must reproduce the above copyright
17
 *    notice, this list of conditions and the following disclaimer in
18
 *    the documentation and/or other materials provided with the
19
 *    distribution.
20
 *
21
 * 3. All advertising materials mentioning features or use of this software
22
 *    must display the following acknowledgment:
23
 *    "This product includes software developed by the pfSense Project
24
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
25
 *
26
 * 4. The names "pfSense" and "pfSense Project" must not be used to
27
 *    endorse or promote products derived from this software without
28
 *    prior written permission. For written permission, please contact
29
 *    coreteam@pfsense.org.
30
 *
31
 * 5. Products derived from this software may not be called "pfSense"
32
 *    nor may "pfSense" appear in their names without prior written
33
 *    permission of the Electric Sheep Fencing, LLC.
34
 *
35
 * 6. Redistributions of any form whatsoever must retain the following
36
 *    acknowledgment:
37
 *
38
 * "This product includes software developed by the pfSense Project
39
 * for use in the pfSense software distribution (http://www.pfsense.org/).
40
 *
41
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
42
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
44
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
45
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
46
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
47
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
48
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
50
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
51
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
52
 * OF THE POSSIBILITY OF SUCH DAMAGE.
53
 */
54

    
55
require_once("config.inc");
56
require_once("rrd.inc");
57

    
58
/* Returns an array of default values used for dpinger */
59
function return_dpinger_defaults() {
60
	return array(
61
		"latencylow" => "200",
62
		"latencyhigh" => "500",
63
		"losslow" => "10",
64
		"losshigh" => "20",
65
		"interval" => "500",
66
		"loss_interval" => "2000",
67
		"time_period" => "60000",
68
		"alert_interval" => "1000",
69
		"data_payload" => "0");
70
}
71

    
72
function running_dpinger_processes() {
73
	global $g;
74

    
75
	$pidfiles = glob("{$g['varrun_path']}/dpinger_*.pid");
76

    
77
	$result = array();
78
	if ($pidfiles === FALSE) {
79
		return $result;
80
	}
81

    
82
	foreach ($pidfiles as $pidfile) {
83
		if (preg_match('/^dpinger_(.+)~([^~]+)~([^~]+)\.pid$/',
84
		    basename($pidfile), $matches)) {
85
			$socket_file = preg_replace('/\.pid$/', '.sock',
86
			    $pidfile);
87
			$result[$matches[1]] = array(
88
			    'srcip'    => $matches[2],
89
			    'targetip' => $matches[3],
90
			    'pidfile'  => $pidfile,
91
			    'socket'   => $socket_file
92
			);
93
			unset($gwinfo);
94
		}
95
	}
96

    
97
	return $result;
98
}
99

    
100
/*
101
 * Stop one or more dpinger process
102
 * default parameter $gwname is '*' that will kill all running sessions
103
 * If a gateway name is passed, only this one will be killed
104
 */
105
function stop_dpinger($gwname = '') {
106
	global $g;
107

    
108
	$running_processes = running_dpinger_processes();
109

    
110
	foreach ($running_processes as $running_gwname => $process) {
111
		if ($gwname != '' && $running_gwname != $gwname) {
112
			continue;
113
		}
114

    
115
		if (isvalidpid($process['pidfile'])) {
116
			killbypid($process['pidfile']);
117
		} else {
118
			@unlink($process['pidfile']);
119
		}
120
	}
121
}
122

    
123
function start_dpinger($gateway) {
124
	global $g;
125

    
126
	if (!isset($gateway['gwifip'])) {
127
		return;
128
	}
129

    
130
	$dpinger_defaults = return_dpinger_defaults();
131

    
132
	$prefix = "{$g['varrun_path']}/dpinger_{$gateway['name']}~" .
133
	    "{$gateway['gwifip']}~{$gateway['monitor']}";
134
	# dpinger socket path should not be longer then uaddr.sun_path
135
	if (strlen($prefix) > 95) {
136
		$prefix = "{$g['varrun_path']}/dpinger_{$gateway['name']}~" .
137
		    substr(md5($gateway['gwifip']),0,8) . "~" .
138
		    $gateway['monitor'];
139
	}
140
	$pidfile = $prefix . ".pid";
141
	$socket = $prefix . ".sock";
142
	$alarm_cmd = "{$g['etc_path']}/rc.gateway_alarm";
143

    
144
	$params  = "-S ";			/* Log warnings via syslog */
145
	$params .= "-r 0 ";			/* Disable unused reporting thread */
146
	$params .= "-i {$gateway['name']} ";	/* Identifier */
147
	$params .= "-B {$gateway['gwifip']} ";	/* Bind src address */
148
	$params .= "-p {$pidfile} ";		/* PID filename */
149
	$params .= "-u {$socket} ";		/* Status Socket */
150
	if (!$gateway['action_disable']) {
151
		$params .= "-C \"{$alarm_cmd}\" ";	/* Command to run on alarm */
152
	}
153

    
154
	$params .= "-d " .
155
	    (isset($gateway['data_payload']) && is_numeric($gateway['data_payload'])
156
	    ? $gateway['data_payload']
157
	    : $dpinger_defaults['data_payload']
158
	    ) . " ";
159

    
160
	$params .= "-s " .
161
	    (isset($gateway['interval']) && is_numeric($gateway['interval'])
162
	    ? $gateway['interval']
163
	    : $dpinger_defaults['interval']
164
	    ) . " ";
165

    
166
	$params .= "-l " .
167
	    (isset($gateway['loss_interval']) && is_numeric($gateway['loss_interval'])
168
	    ?  $gateway['loss_interval']
169
	    : $dpinger_defaults['loss_interval']
170
	    ) . " ";
171

    
172
	$params .= "-t " .
173
	    (isset($gateway['time_period']) && is_numeric($gateway['time_period'])
174
	    ?  $gateway['time_period']
175
	    : $dpinger_defaults['time_period']
176
	    ) . " ";
177

    
178
	$params .= "-A " .
179
	    (isset($gateway['alert_interval']) && is_numeric($gateway['alert_interval'])
180
	    ?  $gateway['alert_interval']
181
	    : $dpinger_defaults['alert_interval']
182
	    ) . " ";
183

    
184
	$params .= "-D " .
185
	    (isset($gateway['latencyhigh']) && is_numeric($gateway['latencyhigh'])
186
	    ?  $gateway['latencyhigh']
187
	    : $dpinger_defaults['latencyhigh']
188
	    ) . " ";
189

    
190
	$params .= "-L " .
191
	    (isset($gateway['losshigh']) && is_numeric($gateway['losshigh'])
192
	    ?  $gateway['losshigh']
193
	    : $dpinger_defaults['losshigh']
194
	    ) . " ";
195

    
196
	/* Make sure we don't end up with 2 process for the same GW */
197
	stop_dpinger($gateway['name']);
198

    
199
	/* Redirect stdout to /dev/null to avoid exec() to wait for dpinger */
200
	return mwexec("/usr/local/bin/dpinger {$params} {$gateway['monitor']} >/dev/null");
201
}
202

    
203
/*
204
 * Starts dpinger processes and adds appropriate static routes for monitor IPs
205
 */
206
function setup_gateways_monitor() {
207
	global $config, $g;
208

    
209
	$gateways_arr = return_gateways_array();
210
	if (!is_array($gateways_arr)) {
211
		log_error(gettext("No gateways to monitor. dpinger will not run."));
212
		stop_dpinger();
213
		return;
214
	}
215

    
216
	$monitor_ips = array();
217
	foreach ($gateways_arr as $gwname => $gateway) {
218
		/* Do not monitor if such was requested */
219
		if (isset($gateway['monitor_disable'])) {
220
			continue;
221
		}
222
		if (empty($gateway['monitor']) || !is_ipaddr($gateway['monitor'])) {
223
			if (is_ipaddr($gateway['gateway'])) {
224
				$gateways_arr[$gwname]['monitor'] = $gateway['gateway'];
225
			} else { /* No chance to get an ip to monitor skip target. */
226
				continue;
227
			}
228
		}
229

    
230
		/* if the monitor address is already used before, skip */
231
		if (in_array($gateway['monitor'], $monitor_ips)) {
232
			continue;
233
		}
234

    
235
		/* Interface ip is needed since dpinger will bind a socket to it.
236
		 * However the config GUI should already have checked this and when
237
		 * PPPoE is used the IP address is set to "dynamic". So using is_ipaddrv4
238
		 * or is_ipaddrv6 to identify packet type would be wrong, especially as
239
		 * further checks (that can cope with the "dynamic" case) are present inside
240
		 * the if block. So using $gateway['ipprotocol'] is the better option.
241
		 */
242
		if ($gateway['ipprotocol'] == "inet") { // This is an IPv4 gateway...
243
			$gwifip = find_interface_ip($gateway['interface'], true);
244
			if (!is_ipaddrv4($gwifip)) {
245
				continue; //Skip this target
246
			}
247

    
248
			if ($gwifip == "0.0.0.0") {
249
				continue; //Skip this target - the gateway is still waiting for DHCP
250
			}
251

    
252
			/*
253
			 * If the gateway is the same as the monitor we do not add a
254
			 * route as this will break the routing table.
255
			 * Add static routes for each gateway with their monitor IP
256
			 * not strictly necessary but is a added level of protection.
257
			 */
258
			if (is_ipaddrv4($gateway['gateway']) && $gateway['monitor'] != $gateway['gateway']) {
259
				log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
260
				if (interface_isppp_type($gateway['friendlyiface'])) {
261
					mwexec("/sbin/route change -host " . escapeshellarg($gateway['monitor']) .
262
						" -iface " . escapeshellarg($gateway['interface']), true);
263
				} else {
264
					mwexec("/sbin/route change -host " . escapeshellarg($gateway['monitor']) .
265
						" " . escapeshellarg($gateway['gateway']), true);
266
				}
267

    
268
				pfSense_kill_states("0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmp");
269
			}
270
		} else if ($gateway['ipprotocol'] == "inet6") { // This is an IPv6 gateway...
271
			if (is_linklocal($gateway['gateway']) &&
272
			    get_ll_scope($gateway['gateway']) == '') {
273
				$gateway['gateway'] .= '%' . $gateway['interface'];
274
			}
275

    
276
			if (is_linklocal($gateway['monitor'])) {
277
				if (get_ll_scope($gateway['monitor']) == '') {
278
					$gateways_arr[$gwname]['monitor'] .= '%' . $gateway['interface'];
279
				}
280

    
281
				$gwifip = find_interface_ipv6_ll($gateway['interface'], true);
282

    
283
				if (get_ll_scope($gwifip) == '') {
284
					$gwifip .= '%' . $gateway['interface'];
285
				}
286
			} else {
287
				$gwifip = find_interface_ipv6($gateway['interface'], true);
288
			}
289

    
290
			if (!is_ipaddrv6($gwifip)) {
291
				continue; //Skip this target
292
			}
293

    
294
			/*
295
			 * If the gateway is the same as the monitor we do not add a
296
			 * route as this will break the routing table.
297
			 * Add static routes for each gateway with their monitor IP
298
			 * not strictly necessary but is a added level of protection.
299
			 */
300
			if ($gateway['gateway'] != $gateway['monitor']) {
301
				log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
302
				if (interface_isppp_type($gateway['friendlyiface'])) {
303
					mwexec("/sbin/route change -host -inet6 " . escapeshellarg($gateway['monitor']) .
304
						" -iface " . escapeshellarg($gateway['interface']), true);
305
				} else {
306
					mwexec("/sbin/route change -host -inet6 " . escapeshellarg($gateway['monitor']) .
307
						" " . escapeshellarg($gateway['gateway']), true);
308
				}
309

    
310
				pfSense_kill_states("::0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmpv6");
311
			}
312
		} else {
313
			continue;
314
		}
315

    
316
		$monitor_ips[] = $gateway['monitor'];
317
		$gateways_arr[$gwname]['enable_dpinger'] = true;
318
		$gateways_arr[$gwname]['gwifip'] = $gwifip;
319
	}
320

    
321
	stop_dpinger();
322

    
323
	/* Start new processes */
324
	foreach ($gateways_arr as $gateway) {
325
		if (!isset($gateway['enable_dpinger'])) {
326
			continue;
327
		}
328

    
329
		if (start_dpinger($gateway) != 0) {
330
			log_error(sprintf(gettext("Error starting gateway monitor for %s"), $gateway['name']));
331
		}
332
	}
333

    
334
	return;
335
}
336

    
337
function get_dpinger_status($gwname, $detailed = false) {
338
	global $g;
339

    
340
	$running_processes = running_dpinger_processes();
341

    
342
	if (!isset($running_processes[$gwname])) {
343
		log_error(sprintf(gettext('dpinger: No dpinger session running for gateway %s'), $gwname));
344
		return false;
345
	}
346

    
347
	$proc = $running_processes[$gwname];
348
	unset($running_processes);
349

    
350
	if (!file_exists($proc['socket'])) {
351
		log_error("dpinger: status socket {$proc['socket']} not found");
352
		return false;
353
	}
354

    
355
	$fp = stream_socket_client("unix://{$proc['socket']}", $errno, $errstr, 10);
356
	if (!$fp) {
357
		log_error(sprintf(gettext('dpinger: cannot connect to status socket %1$s - %2$s (%3$s)'), $proc['socket'], $errstr, $errno));
358
		return false;
359
	}
360

    
361
	$status = '';
362
	while (!feof($fp)) {
363
		$status .= fgets($fp, 1024);
364
	}
365
	fclose($fp);
366

    
367
	$r = array();
368
	list(
369
	    $r['gwname'],
370
	    $r['latency_avg'],
371
	    $r['latency_stddev'],
372
	    $r['loss']
373
	) = explode(' ', preg_replace('/\n/', '', $status));
374

    
375
	$r['srcip'] = $proc['srcip'];
376
	$r['targetip'] = $proc['targetip'];
377

    
378
	$gateways_arr = return_gateways_array();
379
	unset($gw);
380
	if (isset($gateways_arr[$gwname])) {
381
		$gw = $gateways_arr[$gwname];
382
	}
383

    
384
	$r['latency_avg'] = round($r['latency_avg']/1000, 3);
385
	$r['latency_stddev'] = round($r['latency_stddev']/1000, 3);
386

    
387
	$r['status'] = "none";
388
	if (isset($gw) && isset($gw['force_down'])) {
389
		$r['status'] = "force_down";
390
	} else if (isset($gw)) {
391
		$settings = return_dpinger_defaults();
392

    
393
		$keys = array(
394
		    'latencylow',
395
		    'latencyhigh',
396
		    'losslow',
397
		    'losshigh'
398
		);
399

    
400
		/* Replace default values by user-defined */
401
		foreach ($keys as $key) {
402
			if (isset($gw[$key]) && is_numeric($gw[$key])) {
403
				$settings[$key] = $gw[$key];
404
			}
405
		}
406

    
407
		if ($r['latency_avg'] > $settings['latencyhigh']) {
408
			if ($detailed) {
409
				$r['status'] = "highdelay";
410
			} else {
411
				$r['status'] = "down";
412
			}
413
		} else if ($r['loss'] > $settings['losshigh']) {
414
			if ($detailed) {
415
				$r['status'] = "highloss";
416
			} else {
417
				$r['status'] = "down";
418
			}
419
		} else if ($r['latency_avg'] > $settings['latencylow']) {
420
			$r['status'] = "delay";
421
		} else if ($r['loss'] > $settings['losslow']) {
422
			$r['status'] = "loss";
423
		}
424
	}
425

    
426
	return $r;
427
}
428

    
429
/* return the status of the dpinger targets as an array */
430
function return_gateways_status($byname = false) {
431
	global $config, $g;
432

    
433
	$dpinger_gws = running_dpinger_processes();
434
	$status = array();
435

    
436
	$gateways_arr = return_gateways_array();
437

    
438
	foreach ($dpinger_gws as $gwname => $gwdata) {
439
		// If action is disabled for this gateway, then we want a detailed status.
440
		// That reports "highdelay" or "highloss" rather than just "down".
441
		// Because reporting the gateway down would be misleading (gateway action is disabled)
442
		$detailed = $gateways_arr[$gwname]['action_disable'];
443
		$dpinger_status = get_dpinger_status($gwname, $detailed);
444
		if ($dpinger_status === false) {
445
			continue;
446
		}
447

    
448
		if ($byname == false) {
449
			$target = $dpinger_status['targetip'];
450
		} else {
451
			$target = $gwname;
452
		}
453

    
454
		$status[$target] = array();
455
		$status[$target]['monitorip'] = $dpinger_status['targetip'];
456
		$status[$target]['srcip'] = $dpinger_status['srcip'];
457
		$status[$target]['name'] = $gwname;
458
		$status[$target]['delay'] = empty($dpinger_status['latency_avg']) ? "0ms" : $dpinger_status['latency_avg'] . "ms";
459
		$status[$target]['stddev'] = empty($dpinger_status['latency_stddev']) ? "0ms" : $dpinger_status['latency_stddev'] . "ms";
460
		$status[$target]['loss'] = empty($dpinger_status['loss']) ? "0.0%" : round($dpinger_status['loss'], 1) . "%";
461
		$status[$target]['status'] = $dpinger_status['status'];
462
	}
463

    
464
	/* tack on any gateways that have monitoring disabled
465
	 * or are down, which could cause gateway groups to fail */
466
	$gateways_arr = return_gateways_array();
467
	foreach ($gateways_arr as $gwitem) {
468
		if (!isset($gwitem['monitor_disable'])) {
469
			continue;
470
		}
471
		if (!is_ipaddr($gwitem['monitor'])) {
472
			$realif = $gwitem['interface'];
473
			$tgtip = get_interface_gateway($realif);
474
			if (!is_ipaddr($tgtip)) {
475
				$tgtip = "none";
476
			}
477
			$srcip = find_interface_ip($realif);
478
		} else {
479
			$tgtip = $gwitem['monitor'];
480
			$srcip = find_interface_ip($realif);
481
		}
482
		if ($byname == true) {
483
			$target = $gwitem['name'];
484
		} else {
485
			$target = $tgtip;
486
		}
487

    
488
		/* failsafe for down interfaces */
489
		if ($target == "none") {
490
			$target = $gwitem['name'];
491
			$status[$target]['name'] = $gwitem['name'];
492
			$status[$target]['delay'] = "0.0ms";
493
			$status[$target]['loss'] = "100.0%";
494
			$status[$target]['status'] = "down";
495
		} else {
496
			$status[$target]['monitorip'] = $tgtip;
497
			$status[$target]['srcip'] = $srcip;
498
			$status[$target]['name'] = $gwitem['name'];
499
			$status[$target]['delay'] = "";
500
			$status[$target]['loss'] = "";
501
			$status[$target]['status'] = "none";
502
		}
503

    
504
		$status[$target]['monitor_disable'] = true;
505
	}
506
	return($status);
507
}
508

    
509
function return_gateways_status_text($byname = false, $brief = false) {
510
	$gwstat = return_gateways_status($byname);
511
	$output = "";
512
	$widths = array();
513
	$col_sep = 2;
514
	if ($brief) {
515
		$collist = array('status' => "Status");
516
	} else {
517
		$collist = array('monitorip' => "Monitor",
518
				'srcip' => "Source",
519
				'delay' => "Delay",
520
				'stddev' => "StdDev",
521
				'loss' => "Loss",
522
				'status' => "Status");
523
	}
524
	foreach ($gwstat as $gw) {
525
		foreach ($gw as $gwdidx => $gwdata) {
526
			if (strlen($gwdata) > $widths[$gwdidx]) {
527
				$widths[$gwdidx] = strlen($gwdata);
528
			}
529
		}
530
	}
531

    
532
	$output .= str_pad("Name", $widths['name'] + $col_sep, " ", STR_PAD_RIGHT);
533
	foreach ($collist as $hdrcol => $hdrdesc) {
534
		if (strlen($hdrdesc) > $widths[$hdrcol]) {
535
			$widths[$hdrcol] = strlen($hdrdesc);
536
		}
537
		$output .= str_pad($hdrdesc, $widths[$hdrcol] + $col_sep, " ", (substr($hdrcol, -2, 2) == "ip") ? STR_PAD_RIGHT : STR_PAD_LEFT);
538
	}
539
	$output .= "\n";
540

    
541
	foreach ($gwstat as $idx => $gw) {
542
		$output .= str_pad($gw['name'], $widths['name'] + $col_sep, " ", STR_PAD_RIGHT);
543
		foreach (array_keys($collist) as $col) {
544
			$output .= str_pad($gw[$col], $widths[$col] + $col_sep, " ", (substr($col, -2, 2) == "ip") ? STR_PAD_RIGHT : STR_PAD_LEFT);
545
		}
546
		$output .= "\n";
547
	}
548

    
549
	return $output;
550
}
551

    
552
/* Return all configured gateways on the system */
553
function return_gateways_array($disabled = false, $localhost = false, $inactive = false) {
554
	global $config, $g;
555

    
556
	$gateways_arr = array();
557
	$gateways_arr_temp = array();
558

    
559
	$found_defaultv4 = 0;
560
	$found_defaultv6 = 0;
561

    
562
	// Ensure the interface cache is up to date first
563
	$interfaces = get_interface_arr(true);
564

    
565
	$i = -1;
566
	/* Process/add all the configured gateways. */
567
	if (is_array($config['gateways']['gateway_item'])) {
568
		foreach ($config['gateways']['gateway_item'] as $gateway) {
569
			/* Increment it here to do not skip items */
570
			$i++;
571

    
572
			if (empty($config['interfaces'][$gateway['interface']])) {
573
				if ($inactive === false) {
574
					continue;
575
				} else {
576
					$gateway['inactive'] = true;
577
				}
578
			}
579
			$wancfg = $config['interfaces'][$gateway['interface']];
580

    
581
			/* skip disabled interfaces */
582
			if ($disabled === false && (!isset($wancfg['enable']))) {
583
				continue;
584
			}
585

    
586
			/* if the gateway is dynamic and we can find the IPv4, Great! */
587
			if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") {
588
				if ($gateway['ipprotocol'] == "inet") {
589
					/* we know which interfaces is dynamic, this should be made a function */
590
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
591
					/* no IP address found, set to dynamic */
592
					if (!is_ipaddrv4($gateway['gateway'])) {
593
						$gateway['gateway'] = "dynamic";
594
					}
595
					$gateway['dynamic'] = true;
596
				}
597

    
598
				/* if the gateway is dynamic and we can find the IPv6, Great! */
599
				else if ($gateway['ipprotocol'] == "inet6") {
600
					/* we know which interfaces is dynamic, this should be made a function, and for v6 too */
601
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
602
					/* no IPv6 address found, set to dynamic */
603
					if (!is_ipaddrv6($gateway['gateway'])) {
604
						$gateway['gateway'] = "dynamic";
605
					}
606
					$gateway['dynamic'] = true;
607
				}
608
			} else {
609
				/* getting this detection right is hard at this point because we still don't
610
				 * store the address family in the gateway item */
611
				if (is_ipaddrv4($gateway['gateway'])) {
612
					$gateway['ipprotocol'] = "inet";
613
				} else if (is_ipaddrv6($gateway['gateway'])) {
614
					$gateway['ipprotocol'] = "inet6";
615
				}
616
			}
617

    
618
			if (isset($gateway['monitor_disable'])) {
619
				$gateway['monitor_disable'] = true;
620
			} else if (empty($gateway['monitor'])) {
621
				$gateway['monitor'] = $gateway['gateway'];
622
			}
623

    
624
			if (isset($gateway['action_disable'])) {
625
				$gateway['action_disable'] = true;
626
			}
627

    
628
			$gateway['friendlyiface'] = $gateway['interface'];
629

    
630
			/* special treatment for tunnel interfaces */
631
			if ($gateway['ipprotocol'] == "inet6") {
632
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet6", false, false);
633
			} else {
634
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet", false, false);
635
			}
636

    
637
			/* entry has a default flag, use it */
638
			if (isset($gateway['defaultgw'])) {
639
				if ($gateway['ipprotocol'] == "inet") {
640
					$gateway['defaultgw'] = true;
641
					$found_defaultv4 = 1;
642
				} else if ($gateway['ipprotocol'] == "inet6") {
643
					$gateway['defaultgw'] = true;
644
					$found_defaultv6 = 1;
645
				}
646
			}
647
			/* include the gateway index as the attribute */
648
			$gateway['attribute'] = $i;
649

    
650
			/* Remember all the gateway names, even ones to be skipped because they are disabled. */
651
			/* Then we can easily know and match them later when attempting to add dynamic gateways to the list. */
652
			$gateways_arr_temp[$gateway['name']] = $gateway;
653

    
654
			/* skip disabled gateways if the caller has not asked for them to be returned. */
655
			if (!($disabled === false && isset($gateway['disabled']))) {
656
				$gateways_arr[$gateway['name']] = $gateway;
657
			}
658
		}
659
	}
660
	unset($gateway);
661

    
662
	/* Loop through all interfaces with a gateway and add it to a array */
663
	if ($disabled == false) {
664
		$iflist = get_configured_interface_with_descr();
665
	} else {
666
		$iflist = get_configured_interface_with_descr(false, true);
667
	}
668

    
669
	/* Process/add dynamic v4 gateways. */
670
	foreach ($iflist as $ifname => $friendly) {
671
		if (!interface_has_gateway($ifname)) {
672
			continue;
673
		}
674

    
675
		if (empty($config['interfaces'][$ifname])) {
676
			continue;
677
		}
678

    
679
		$ifcfg = &$config['interfaces'][$ifname];
680
		if (!isset($ifcfg['enable'])) {
681
			continue;
682
		}
683

    
684
		if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) {
685
			continue;
686
		}
687

    
688
		$ctype = "";
689
		switch ($ifcfg['ipaddr']) {
690
			case "dhcp":
691
			case "pppoe":
692
			case "l2tp":
693
			case "pptp":
694
			case "ppp":
695
				$ctype = strtoupper($ifcfg['ipaddr']);
696
				break;
697
			default:
698
				$tunnelif = substr($ifcfg['if'], 0, 3);
699
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
700
					// if current iface is an ovpn server endpoint then check its type, skip tap only
701
					if (substr($ifcfg['if'], 4, 1) == 's') {
702
						$ovpnid = substr($ifcfg['if'], 5);
703
						if (is_array($config['openvpn']['openvpn-server'])) {
704
							foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) {
705
								if ($ovpnserverconf['vpnid'] == $ovpnid) {
706
									if ($ovpnserverconf['dev_mode'] == "tap") {
707
										continue 3;
708
									}
709
								}
710
							}
711
						}
712
					}
713
					$ctype = "VPNv4";
714
				} else if ($tunnelif == "gif" || $tunnelif == "gre") {
715
					$ctype = "TUNNELv4";
716
				}
717
				break;
718
		}
719
		$ctype = "_". strtoupper($ctype);
720

    
721
		$gateway = array();
722
		$gateway['dynamic'] = false;
723
		$gateway['ipprotocol'] = "inet";
724
		$gateway['gateway'] = get_interface_gateway($ifname, $gateway['dynamic']);
725
		$gateway['interface'] = get_real_interface($ifname);
726
		$gateway['friendlyiface'] = $ifname;
727
		$gateway['name'] = "{$friendly}{$ctype}";
728
		$gateway['attribute'] = "system";
729

    
730
		if (($gateway['dynamic'] === "default") && ($found_defaultv4 == 0)) {
731
			$gateway['defaultgw'] = true;
732
			$gateway['dynamic'] = true;
733
			$found_defaultv4 = 1;
734
		}
735
		/* Loopback dummy for dynamic interfaces without a IP */
736
		if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) {
737
			$gateway['gateway'] = "dynamic";
738
		}
739

    
740
		/* automatically skip known static and dynamic gateways that were previously processed */
741
		foreach ($gateways_arr_temp as $gateway_item) {
742
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
743
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
744
				continue 2;
745
			}
746
		}
747

    
748
		if (is_ipaddrv4($gateway['gateway'])) {
749
			$gateway['monitor'] = $gateway['gateway'];
750
		}
751

    
752
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
753
		$gateways_arr[$gateway['name']] = $gateway;
754
	}
755
	unset($gateway);
756

    
757
	/* Process/add dynamic v6 gateways. */
758
	foreach ($iflist as $ifname => $friendly) {
759
		/* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */
760
		if (!isset($config['system']['ipv6allow'])) {
761
			break;
762
		}
763

    
764
		if (!interface_has_gatewayv6($ifname)) {
765
			continue;
766
		}
767

    
768
		if (empty($config['interfaces'][$ifname])) {
769
			continue;
770
		}
771

    
772
		$ifcfg = &$config['interfaces'][$ifname];
773
		if (!isset($ifcfg['enable'])) {
774
			continue;
775
		}
776

    
777
		if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) {
778
			continue;
779
		}
780

    
781
		$ctype = "";
782
		switch ($ifcfg['ipaddrv6']) {
783
			case "slaac":
784
			case "dhcp6":
785
			case "6to4":
786
			case "6rd":
787
				$ctype = strtoupper($ifcfg['ipaddrv6']);
788
				break;
789
			default:
790
				$tunnelif = substr($ifcfg['if'], 0, 3);
791
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
792
					// if current iface is an ovpn server endpoint then check its type, skip tap only
793
					if (substr($ifcfg['if'], 4, 1) == 's') {
794
						$ovpnid = substr($ifcfg['if'], 5);
795
						if (is_array($config['openvpn']['openvpn-server'])) {
796
							foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) {
797
								if ($ovpnserverconf['vpnid'] == $ovpnid) {
798
									if ($ovpnserverconf['dev_mode'] == "tap") {
799
										continue 3;
800
									}
801
								}
802
							}
803
						}
804
					}
805
					$ctype = "VPNv6";
806
				} else if ($tunnelif == "gif" || $tunnelif == "gre") {
807
					$ctype = "TUNNELv6";
808
				}
809
				break;
810
		}
811
		$ctype = "_". strtoupper($ctype);
812

    
813
		$gateway = array();
814
		$gateway['dynamic'] = false;
815
		$gateway['ipprotocol'] = "inet6";
816
		$gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']);
817
		$gateway['interface'] = get_real_interface($ifname, "inet6");
818
		switch ($ifcfg['ipaddrv6']) {
819
			case "6rd":
820
			case "6to4":
821
				$gateway['dynamic'] = "default";
822
				break;
823
		}
824
		$gateway['friendlyiface'] = $ifname;
825
		$gateway['name'] = "{$friendly}{$ctype}";
826
		$gateway['attribute'] = "system";
827

    
828
		if (($gateway['dynamic'] === "default") && ($found_defaultv6 == 0)) {
829
			$gateway['defaultgw'] = true;
830
			$gateway['dynamic'] = true;
831
			$found_defaultv6 = 1;
832
		}
833

    
834
		/* Loopback dummy for dynamic interfaces without a IP */
835
		if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) {
836
			$gateway['gateway'] = "dynamic";
837
		}
838

    
839
		/* automatically skip known static and dynamic gateways that were previously processed */
840
		foreach ($gateways_arr_temp as $gateway_item) {
841
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
842
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
843
				continue 2;
844
			}
845
		}
846

    
847
		if (is_ipaddrv6($gateway['gateway'])) {
848
			$gateway['monitor'] = $gateway['gateway'];
849
		}
850

    
851
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
852
		$gateways_arr[$gateway['name']] = $gateway;
853
	}
854
	unset($gateway);
855

    
856
	/* FIXME: Should this be enabled.
857
	 * Some interface like wan might be default but have no info recorded
858
	 * the config. */
859
	/* this is a fallback if all else fails and we want to get packets out @smos */
860
	if ($found_defaultv4 == 0 || $found_defaultv6 == 0) {
861
		foreach ($gateways_arr as &$gateway) {
862
			if (($gateway['friendlyiface'] == "wan") && ($found_defaultv4 == 0) && (!isset($gateway['ipprotocol']) || ($gateway['ipprotocol'] == "inet"))) {
863
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgw")) {
864
					$gateway['defaultgw'] = true;
865
					$found_defaultv4 = 1;
866
				}
867
			}
868
			else if (($gateway['friendlyiface'] == "wan") && ($found_defaultv6 == 0) && ($gateway['ipprotocol'] == "inet6")) {
869
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgwv6")) {
870
					$gateway['defaultgw'] = true;
871
					$found_defaultv6 = 1;
872
				}
873
			}
874
		}
875
	}
876

    
877
	if ($localhost === true) {
878
		/* attach localhost for Null routes */
879
		$gwlo4 = array();
880
		$gwlo4['name'] = "Null4";
881
		$gwlo4['interface'] = "lo0";
882
		$gwlo4['ipprotocol'] = "inet";
883
		$gwlo4['gateway'] = "127.0.0.1";
884
		$gwlo6 = array();
885
		$gwlo6['name'] = "Null6";
886
		$gwlo6['interface'] = "lo0";
887
		$gwlo6['ipprotocol'] = "inet6";
888
		$gwlo6['gateway'] = "::1";
889
		$gateways_arr['Null4'] = $gwlo4;
890
		$gateways_arr['Null6'] = $gwlo6;
891
	}
892
	return($gateways_arr);
893
}
894

    
895
function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
896
	global $config, $g;
897
	/*
898
	 * NOTE: The code below is meant to replace the default gateway when it goes down.
899
	 *	This facilitates services running on pfSense itself and are not handled by a PBR to continue working.
900
	 */
901
	$upgw = '';
902
	$dfltgwname = '';
903
	$dfltgwdown = false;
904
	$dfltgwfound = false;
905
	foreach ($gateways_arr as $gwname => $gwsttng) {
906
		if (($gwsttng['ipprotocol'] == $ipprotocol) && isset($gwsttng['defaultgw'])) {
907
			$dfltgwfound = true;
908
			$dfltgwname = $gwname;
909
			if (!isset($gwsttng['monitor_disable']) && !isset($gwsttng['action_disable']) && $gateways_status[$gwname]['status'] != "none") {
910
				$dfltgwdown = true;
911
			}
912
		}
913
		/* Keep a record of the last up gateway */
914
		/* XXX: Blacklist lan for now since it might cause issues to those who have a gateway set for it */
915
		if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || isset($gwsttng['action_disable']) || $gateways_status[$gwname]['status'] == "none") && $gwsttng[$gwname]['friendlyiface'] != "lan") {
916
			$upgw = $gwname;
917
		}
918
		if ($dfltgwdown == true && !empty($upgw)) {
919
			break;
920
		}
921
	}
922
	if ($dfltgwfound == false) {
923
		$gwname = convert_friendly_interface_to_friendly_descr("wan");
924
		if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down")) {
925
			$dfltgwdown = true;
926
		}
927
	}
928
	if ($dfltgwdown == true && !empty($upgw)) {
929
		if ($gateways_arr[$upgw]['gateway'] == "dynamic") {
930
			$gateways_arr[$upgw]['gateway'] = get_interface_gateway($gateways_arr[$upgw]['friendlyiface']);
931
		}
932
		if (is_ipaddr($gateways_arr[$upgw]['gateway'])) {
933
			log_error("Default gateway down setting {$upgw} as default!");
934
			if (is_ipaddrv6($gateways_arr[$upgw]['gateway'])) {
935
				$inetfamily = "-inet6";
936
				if (is_linklocal($gateways_arr[$upgw]['gateway']) && get_ll_scope($gateways_arr[$upgw]['gateway']) == '') {
937
					$gateways_arr[$upgw]['gateway'] .= "%" . $gateways_arr[$upgw]['interface'];
938
				}
939
			} else {
940
				$inetfamily = "-inet";
941
			}
942
			mwexec("/sbin/route change {$inetfamily} default {$gateways_arr[$upgw]['gateway']}");
943
		}
944
	} else if (!empty($dfltgwname)) {
945
		$defaultgw = trim(exec("/sbin/route -n get -{$ipprotocol} default | /usr/bin/awk '/gateway:/ {print $2}'"), " \n");
946
		if ($ipprotocol == 'inet6' && !is_ipaddrv6($gateways_arr[$dfltgwname]['gateway'])) {
947
			return;
948
		}
949
		if ($ipprotocol == 'inet' && !is_ipaddrv4($gateways_arr[$dfltgwname]['gateway'])) {
950
			return;
951
		}
952
		if ($ipprotocol == 'inet6') {
953
			if (is_linklocal($gateways_arr[$upgw]['gateway']) && get_ll_scope($gateways_arr[$upgw]['gateway']) == '') {
954
				$gateways_arr[$upgw]['gateway'] .= "%" . $gateways_arr[$upgw]['interface'];
955
			}
956
			if (is_linklocal($gateways_arr[$dfltgwname]['gateway']) && get_ll_scope($gateways_arr[$dfltgwname]['gateway']) == '') {
957
				$gateways_arr[$dfltgwname]['gateway'] .= "%" . $gateways_arr[$dfltgwname]['interface'];
958
			}
959
		}
960
		if ($defaultgw != $gateways_arr[$dfltgwname]['gateway']) {
961
			mwexec("/sbin/route change -{$ipprotocol} default {$gateways_arr[$dfltgwname]['gateway']}");
962
		}
963
	}
964
}
965

    
966
/*
967
 * Return an array with all gateway groups with name as key
968
 * All gateway groups will be processed before returning the array.
969
 */
970
function return_gateway_groups_array() {
971
	global $config, $g;
972

    
973
	/* fetch the current gateways status */
974
	$gateways_status = return_gateways_status(true);
975
	$gateways_arr = return_gateways_array();
976
	$gateway_groups_array = array();
977

    
978
	if (isset($config['system']['gw_switch_default'])) {
979
		fixup_default_gateway("inet", $gateways_status, $gateways_arr);
980
		fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
981
	}
982
	if (is_array($config['gateways']['gateway_group'])) {
983
		$viplist = get_configured_vip_list();
984
		foreach ($config['gateways']['gateway_group'] as $group) {
985
			$gateway_groups_array[$group['name']]['descr'] = $group['descr'];
986
			/* create array with group gateways members separated by tier */
987
			$tiers = array();
988
			$backupplan = array();
989
			$gwvip_arr = array();
990
			foreach ($group['item'] as $item) {
991
				list($gwname, $tier, $vipname) = explode("|", $item);
992

    
993
				if (is_ipaddr($viplist[$vipname])) {
994
					if (!is_array($gwvip_arr[$group['name']])) {
995
						$gwvip_arr[$group['name']] = array();
996
					}
997
					$gwvip_arr[$group['name']][$gwname] = $vipname;
998
				}
999

    
1000
				/* Do it here rather than reiterating again the group in case no member is up. */
1001
				if (!is_array($backupplan[$tier])) {
1002
					$backupplan[$tier] = array();
1003
				}
1004
				$backupplan[$tier][] = $gwname;
1005

    
1006
				/* check if the gateway is available before adding it to the array */
1007
				if (is_array($gateways_status[$gwname])) {
1008
					$status = $gateways_status[$gwname];
1009
					$gwdown = false;
1010
					if (stristr($status['status'], "down")) {
1011
						$msg = sprintf(gettext('MONITOR: %1$s is down, omitting from routing group %2$s'), $gwname, $group['name']);
1012
						$gwdown = true;
1013
					} else if (stristr($status['status'], "loss") && strstr($group['trigger'], "loss")) {
1014
						/* packet loss */
1015
						$msg = sprintf(gettext('MONITOR: %1$s has packet loss, omitting from routing group %2$s'), $gwname, $group['name']);
1016
						$gwdown = true;
1017
					} else if (stristr($status['status'], "delay") && strstr($group['trigger'] , "latency")) {
1018
						/* high latency */
1019
						$msg = sprintf(gettext('MONITOR: %1$s has high latency, omitting from routing group %2$s'), $gwname, $group['name']);
1020
						$gwdown = true;
1021
					}
1022
					if ($gwdown == true) {
1023
						if (!file_exists("/tmp/.down.{$gwname}")) {
1024
							$msg .= "\n".implode("|", $status);
1025
							touch("/tmp/.down.{$gwname}");
1026
							log_error($msg);
1027
							notify_via_growl($msg);
1028
							notify_via_smtp($msg);
1029
						}
1030
					} else {
1031
						/* Online add member */
1032
						if (!is_array($tiers[$tier])) {
1033
							$tiers[$tier] = array();
1034
						}
1035
						$tiers[$tier][] = $gwname;
1036
						if (unlink_if_exists("/tmp/.down.{$gwname}")) {
1037
							$msg = sprintf(gettext('MONITOR: %1$s is available now, adding to routing group %2$s'), $gwname, $group['name']);
1038
							$msg .= "\n".implode("|", $status);
1039
							log_error($msg);
1040
							notify_via_growl($msg);
1041
							notify_via_smtp($msg);
1042
						}
1043
					}
1044
				} else if (isset($gateways_arr[$gwname]['monitor_disable']) || isset($gateways_arr[$gwname]['action_disable'])) {
1045
					$tiers[$tier][] = $gwname;
1046
				}
1047
			}
1048
			$tiers_count = count($tiers);
1049
			if ($tiers_count == 0) {
1050
				/* Oh dear, we have no members! Engage Plan B */
1051
				if (!platform_booting()) {
1052
					$msg = sprintf(gettext('Gateways status could not be determined, considering all as up/active. (Group: %s)'), $group['name']);
1053
					log_error($msg);
1054
					notify_via_growl($msg);
1055
					//notify_via_smtp($msg);
1056
				}
1057
				$tiers = $backupplan;
1058
			}
1059
			/* sort the tiers array by the tier key */
1060
			ksort($tiers);
1061

    
1062
			/* we do not really foreach the tiers as we stop after the first tier */
1063
			foreach ($tiers as $tieridx => $tier) {
1064
				/* process all gateways in this tier */
1065
				foreach ($tier as $member) {
1066
					/* determine interface gateway */
1067
					if (isset($gateways_arr[$member])) {
1068
						$gateway = $gateways_arr[$member];
1069
						$int = $gateway['interface'];
1070
						$gatewayip = "";
1071
						if (is_ipaddr($gateway['gateway'])) {
1072
							$gatewayip = $gateway['gateway'];
1073
						} else if (!empty($int)) {
1074
							$gatewayip = get_interface_gateway($gateway['friendlyiface']);
1075
						}
1076

    
1077
						if (!empty($int)) {
1078
							$gateway_groups_array[$group['name']]['ipprotocol'] = $gateway['ipprotocol'];
1079
							if (is_ipaddr($gatewayip)) {
1080
								$groupmember = array();
1081
								$groupmember['int'] = $int;
1082
								$groupmember['gwip'] = $gatewayip;
1083
								$groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1;
1084
								if (is_array($gwvip_arr[$group['name']]) && !empty($gwvip_arr[$group['name']][$member]))
1085
									$groupmember['vip'] = $gwvip_arr[$group['name']][$member];
1086
								$gateway_groups_array[$group['name']][] = $groupmember;
1087
							}
1088
						}
1089
					}
1090
				}
1091
				/* we should have the 1st available tier now, exit stage left */
1092
				if (count($gateway_groups_array[$group['name']]) > 0) {
1093
					break;
1094
				} else {
1095
					log_error(sprintf(gettext('GATEWAYS: Group %1$s did not have any gateways up on tier %2$s!'), $group['name'], $tieridx));
1096
				}
1097
			}
1098
		}
1099
	}
1100

    
1101
	return ($gateway_groups_array);
1102
}
1103

    
1104
/* Update DHCP WAN Interface ip address in gateway group item */
1105
function dhclient_update_gateway_groups_defaultroute($interface = "wan") {
1106
	global $config, $g;
1107
	foreach ($config['gateways']['gateway_item'] as & $gw) {
1108
		if ($gw['interface'] == $interface) {
1109
			$current_gw = get_interface_gateway($interface);
1110
			if ($gw['gateway'] <> $current_gw) {
1111
				$gw['gateway'] = $current_gw;
1112
				$changed = true;
1113
			}
1114
		}
1115
	}
1116
	if ($changed && $current_gw) {
1117
		write_config(sprintf(gettext('Updating gateway group gateway for %1$s - new gateway is %2$s'), $interface, $current_gw));
1118
	}
1119
}
1120

    
1121
function lookup_gateway_ip_by_name($name, $disabled = false) {
1122

    
1123
	$gateways_arr = return_gateways_array($disabled, true);
1124
	foreach ($gateways_arr as $gname => $gw) {
1125
		if ($gw['name'] === $name || $gname === $name) {
1126
			return $gw['gateway'];
1127
		}
1128
	}
1129

    
1130
	return false;
1131
}
1132

    
1133
function lookup_gateway_monitor_ip_by_name($name) {
1134

    
1135
	$gateways_arr = return_gateways_array(false, true);
1136
	if (!empty($gateways_arr[$name])) {
1137
		$gateway = $gateways_arr[$name];
1138
		if (!is_ipaddr($gateway['monitor'])) {
1139
			return $gateway['gateway'];
1140
		}
1141

    
1142
		return $gateway['monitor'];
1143
	}
1144

    
1145
	return (false);
1146
}
1147

    
1148
function lookup_gateway_interface_by_name($name) {
1149

    
1150
	$gateways_arr = return_gateways_array(false, true);
1151
	if (!empty($gateways_arr[$name])) {
1152
		$interfacegw = $gateways_arr[$name]['friendlyiface'];
1153
		return ($interfacegw);
1154
	}
1155

    
1156
	return (false);
1157
}
1158

    
1159
function get_interface_gateway($interface, &$dynamic = false) {
1160
	global $config, $g;
1161

    
1162
	if (substr($interface, 0, 4) == '_vip') {
1163
		$interface = get_configured_vip_interface($interface);
1164
		if (substr($interface, 0, 4) == '_vip') {
1165
			$interface = get_configured_vip_interface($interface);
1166
		}
1167
	}
1168

    
1169
	$gw = NULL;
1170
	$gwcfg = $config['interfaces'][$interface];
1171
	if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) {
1172
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1173
			if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
1174
				$gw = $gateway['gateway'];
1175
				break;
1176
			}
1177
		}
1178
	}
1179

    
1180
	// for dynamic interfaces we handle them through the $interface_router file.
1181
	if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) {
1182
		$realif = get_real_interface($interface);
1183
		if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
1184
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
1185
			$dynamic = true;
1186
		}
1187
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) {
1188
			$dynamic = "default";
1189
		}
1190

    
1191
	}
1192

    
1193
	/* return gateway */
1194
	return ($gw);
1195
}
1196

    
1197
function get_interface_gateway_v6($interface, &$dynamic = false) {
1198
	global $config, $g;
1199

    
1200
	if (substr($interface, 0, 4) == '_vip') {
1201
		$interface = get_configured_vip_interface($interface);
1202
		if (substr($interface, 0, 4) == '_vip') {
1203
			$interface = get_configured_vip_interface($interface);
1204
		}
1205
	}
1206

    
1207
	$gw = NULL;
1208
	$gwcfg = $config['interfaces'][$interface];
1209
	if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) {
1210
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1211
			if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
1212
				$gw = $gateway['gateway'];
1213
				break;
1214
			}
1215
		}
1216
	}
1217

    
1218
	// for dynamic interfaces we handle them through the $interface_router file.
1219
	if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) {
1220
		$realif = get_real_interface($interface);
1221
		if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
1222
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
1223
			$dynamic = true;
1224
		}
1225
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) {
1226
			$dynamic = "default";
1227
		}
1228
	}
1229
	/* return gateway */
1230
	return ($gw);
1231
}
1232

    
1233
/* Check a IP address against a gateway IP or name
1234
 * to verify it's address family */
1235
function validate_address_family($ipaddr, $gwname, $disabled = false) {
1236
	$v4ip = false;
1237
	$v6ip = false;
1238
	$v4gw = false;
1239
	$v6gw = false;
1240

    
1241
	if (is_ipaddrv4($ipaddr)) {
1242
		$v4ip = true;
1243
	}
1244
	if (is_ipaddrv6($ipaddr)) {
1245
		$v6ip = true;
1246
	}
1247
	if (is_ipaddrv4($gwname)) {
1248
		$v4gw = true;
1249
	}
1250
	if (is_ipaddrv6($gwname)) {
1251
		$v6gw = true;
1252
	}
1253

    
1254
	if ($v4ip && $v4gw) {
1255
		return true;
1256
	}
1257
	if ($v6ip && $v6gw) {
1258
		return true;
1259
	}
1260

    
1261
	/* still no match, carry on, lookup gateways */
1262
	if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname, $disabled))) {
1263
		$v4gw = true;
1264
	}
1265
	if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname, $disabled))) {
1266
		$v6gw = true;
1267
	}
1268

    
1269
	$gw_array = return_gateways_array();
1270
	if (is_array($gw_array[$gwname])) {
1271
		switch ($gw_array[$gwname]['ipprotocol']) {
1272
			case "inet":
1273
				$v4gw = true;
1274
				break;
1275
			case "inet6":
1276
				$v6gw = true;
1277
				break;
1278
		}
1279
	}
1280

    
1281
	if ($v4ip && $v4gw) {
1282
		return true;
1283
	}
1284
	if ($v6ip && $v6gw) {
1285
		return true;
1286
	}
1287

    
1288
	return false;
1289
}
1290

    
1291
/* check if a interface is part of a gateway group */
1292
function interface_gateway_group_member($interface) {
1293
	global $config;
1294

    
1295
	if (is_array($config['gateways']['gateway_group'])) {
1296
		$groups = $config['gateways']['gateway_group'];
1297
	} else {
1298
		return false;
1299
	}
1300

    
1301
	$gateways_arr = return_gateways_array(false, true);
1302
	foreach ($groups as $group) {
1303
		if (is_array($group['item'])) {
1304
			foreach ($group['item'] as $item) {
1305
				$elements = explode("|", $item);
1306
				$gwname = $elements[0];
1307
				if ($interface == $gateways_arr[$gwname]['interface']) {
1308
					unset($gateways_arr);
1309
					return true;
1310
				}
1311
			}
1312
		}
1313
	}
1314
	unset($gateways_arr);
1315

    
1316
	return false;
1317
}
1318

    
1319
function gateway_is_gwgroup_member($name) {
1320
	global $config;
1321

    
1322
	if (is_array($config['gateways']['gateway_group'])) {
1323
		$groups = $config['gateways']['gateway_group'];
1324
	} else {
1325
		return false;
1326
	}
1327

    
1328
	$members = array();
1329
	foreach ($groups as $group) {
1330
		if (is_array($group['item'])) {
1331
			foreach ($group['item'] as $item) {
1332
				$elements = explode("|", $item);
1333
				$gwname = $elements[0];
1334
				if ($name == $elements[0]) {
1335
					$members[] = $group['name'];
1336
				}
1337
			}
1338
		}
1339
	}
1340

    
1341
	return $members;
1342
}
1343
?>
(24-24/65)