Project

General

Profile

Download (40.1 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
 * Licensed under the Apache License, Version 2.0 (the "License");
11
 * you may not use this file except in compliance with the License.
12
 * You may obtain a copy of the License at
13
 *
14
 * http://www.apache.org/licenses/LICENSE-2.0
15
 *
16
 * Unless required by applicable law or agreed to in writing, software
17
 * distributed under the License is distributed on an "AS IS" BASIS,
18
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
 * See the License for the specific language governing permissions and
20
 * limitations under the License.
21
 */
22

    
23
require_once("config.inc");
24
require_once("rrd.inc");
25

    
26
/* Returns an array of default values used for dpinger */
27
function return_dpinger_defaults() {
28
	return array(
29
		"latencylow" => "200",
30
		"latencyhigh" => "500",
31
		"losslow" => "10",
32
		"losshigh" => "20",
33
		"interval" => "500",
34
		"loss_interval" => "2000",
35
		"time_period" => "60000",
36
		"alert_interval" => "1000",
37
		"data_payload" => "0");
38
}
39

    
40
function running_dpinger_processes() {
41
	global $g;
42

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

    
45
	$result = array();
46
	if ($pidfiles === FALSE) {
47
		return $result;
48
	}
49

    
50
	foreach ($pidfiles as $pidfile) {
51
		if (preg_match('/^dpinger_(.+)~([^~]+)~([^~]+)\.pid$/',
52
		    basename($pidfile), $matches)) {
53
			$socket_file = preg_replace('/\.pid$/', '.sock',
54
			    $pidfile);
55
			$result[$matches[1]] = array(
56
			    'srcip'    => $matches[2],
57
			    'targetip' => $matches[3],
58
			    'pidfile'  => $pidfile,
59
			    'socket'   => $socket_file
60
			);
61
			unset($gwinfo);
62
		}
63
	}
64

    
65
	return $result;
66
}
67

    
68
/*
69
 * Stop one or more dpinger process
70
 * default parameter $gwname is '*' that will kill all running sessions
71
 * If a gateway name is passed, only this one will be killed
72
 */
73
function stop_dpinger($gwname = '') {
74
	global $g;
75

    
76
	$running_processes = running_dpinger_processes();
77

    
78
	foreach ($running_processes as $running_gwname => $process) {
79
		if ($gwname != '' && $running_gwname != $gwname) {
80
			continue;
81
		}
82

    
83
		if (isvalidpid($process['pidfile'])) {
84
			killbypid($process['pidfile']);
85
		} else {
86
			@unlink($process['pidfile']);
87
		}
88
	}
89
}
90

    
91
function start_dpinger($gateway) {
92
	global $g;
93

    
94
	if (!isset($gateway['gwifip'])) {
95
		return;
96
	}
97

    
98
	$dpinger_defaults = return_dpinger_defaults();
99

    
100
	$prefix = "{$g['varrun_path']}/dpinger_{$gateway['name']}~" .
101
	    "{$gateway['gwifip']}~{$gateway['monitor']}";
102
	# dpinger socket path should not be longer then uaddr.sun_path
103
	if (strlen($prefix) > 95) {
104
		$prefix = "{$g['varrun_path']}/dpinger_{$gateway['name']}~" .
105
		    substr(md5($gateway['gwifip']),0,8) . "~" .
106
		    $gateway['monitor'];
107
	}
108
	$pidfile = $prefix . ".pid";
109
	$socket = $prefix . ".sock";
110
	$alarm_cmd = "{$g['etc_path']}/rc.gateway_alarm";
111

    
112
	$params  = "-S ";			/* Log warnings via syslog */
113
	$params .= "-r 0 ";			/* Disable unused reporting thread */
114
	$params .= "-i {$gateway['name']} ";	/* Identifier */
115
	$params .= "-B {$gateway['gwifip']} ";	/* Bind src address */
116
	$params .= "-p {$pidfile} ";		/* PID filename */
117
	$params .= "-u {$socket} ";		/* Status Socket */
118
	if (!$gateway['action_disable']) {
119
		$params .= "-C \"{$alarm_cmd}\" ";	/* Command to run on alarm */
120
	}
121

    
122
	$params .= "-d " .
123
	    (isset($gateway['data_payload']) && is_numeric($gateway['data_payload'])
124
	    ? $gateway['data_payload']
125
	    : $dpinger_defaults['data_payload']
126
	    ) . " ";
127

    
128
	$params .= "-s " .
129
	    (isset($gateway['interval']) && is_numeric($gateway['interval'])
130
	    ? $gateway['interval']
131
	    : $dpinger_defaults['interval']
132
	    ) . " ";
133

    
134
	$params .= "-l " .
135
	    (isset($gateway['loss_interval']) && is_numeric($gateway['loss_interval'])
136
	    ?  $gateway['loss_interval']
137
	    : $dpinger_defaults['loss_interval']
138
	    ) . " ";
139

    
140
	$params .= "-t " .
141
	    (isset($gateway['time_period']) && is_numeric($gateway['time_period'])
142
	    ?  $gateway['time_period']
143
	    : $dpinger_defaults['time_period']
144
	    ) . " ";
145

    
146
	$params .= "-A " .
147
	    (isset($gateway['alert_interval']) && is_numeric($gateway['alert_interval'])
148
	    ?  $gateway['alert_interval']
149
	    : $dpinger_defaults['alert_interval']
150
	    ) . " ";
151

    
152
	$params .= "-D " .
153
	    (isset($gateway['latencyhigh']) && is_numeric($gateway['latencyhigh'])
154
	    ?  $gateway['latencyhigh']
155
	    : $dpinger_defaults['latencyhigh']
156
	    ) . " ";
157

    
158
	$params .= "-L " .
159
	    (isset($gateway['losshigh']) && is_numeric($gateway['losshigh'])
160
	    ?  $gateway['losshigh']
161
	    : $dpinger_defaults['losshigh']
162
	    ) . " ";
163

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

    
167
	/* Redirect stdout to /dev/null to avoid exec() to wait for dpinger */
168
	return mwexec("/usr/local/bin/dpinger {$params} {$gateway['monitor']} >/dev/null");
169
}
170

    
171
/*
172
 * Starts dpinger processes and adds appropriate static routes for monitor IPs
173
 */
174
function setup_gateways_monitor() {
175
	global $config, $g;
176

    
177
	$gateways_arr = return_gateways_array();
178
	if (!is_array($gateways_arr)) {
179
		log_error(gettext("No gateways to monitor. dpinger will not run."));
180
		stop_dpinger();
181
		return;
182
	}
183

    
184
	$monitor_ips = array();
185
	foreach ($gateways_arr as $gwname => $gateway) {
186
		/* Do not monitor if such was requested */
187
		if (isset($gateway['monitor_disable'])) {
188
			continue;
189
		}
190
		if (empty($gateway['monitor']) || !is_ipaddr($gateway['monitor'])) {
191
			if (is_ipaddr($gateway['gateway'])) {
192
				$gateways_arr[$gwname]['monitor'] = $gateway['gateway'];
193
			} else { /* No chance to get an ip to monitor skip target. */
194
				continue;
195
			}
196
		}
197

    
198
		/* if the monitor address is already used before, skip */
199
		if (in_array($gateway['monitor'], $monitor_ips)) {
200
			continue;
201
		}
202

    
203
		/* Interface ip is needed since dpinger will bind a socket to it.
204
		 * However the config GUI should already have checked this and when
205
		 * PPPoE is used the IP address is set to "dynamic". So using is_ipaddrv4
206
		 * or is_ipaddrv6 to identify packet type would be wrong, especially as
207
		 * further checks (that can cope with the "dynamic" case) are present inside
208
		 * the if block. So using $gateway['ipprotocol'] is the better option.
209
		 */
210
		if ($gateway['ipprotocol'] == "inet") { // This is an IPv4 gateway...
211
			$gwifip = find_interface_ip($gateway['interface'], true);
212
			if (!is_ipaddrv4($gwifip)) {
213
				continue; //Skip this target
214
			}
215

    
216
			if ($gwifip == "0.0.0.0") {
217
				continue; //Skip this target - the gateway is still waiting for DHCP
218
			}
219

    
220
			/*
221
			 * If the gateway is the same as the monitor we do not add a
222
			 * route as this will break the routing table.
223
			 * Add static routes for each gateway with their monitor IP
224
			 * not strictly necessary but is a added level of protection.
225
			 */
226
			if (is_ipaddrv4($gateway['gateway']) && $gateway['monitor'] != $gateway['gateway']) {
227
				log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
228
				$route_to = "-host {$gateway['monitor']}";
229
				if (interface_isppp_type($gateway['friendlyiface'])) {
230
					route_add_or_change("{$route_to} -iface {$gateway['interface']}");
231
				} else {
232
					route_add_or_change("{$route_to} {$gateway['gateway']}");
233
				}
234

    
235
				pfSense_kill_states("0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmp");
236
			}
237
		} else if ($gateway['ipprotocol'] == "inet6") { // This is an IPv6 gateway...
238
			if (is_linklocal($gateway['gateway']) &&
239
			    get_ll_scope($gateway['gateway']) == '') {
240
				$gateway['gateway'] .= '%' . $gateway['interface'];
241
			}
242

    
243
			if (is_linklocal($gateway['monitor'])) {
244
				if (get_ll_scope($gateway['monitor']) == '') {
245
					$gateways_arr[$gwname]['monitor'] .= '%' . $gateway['interface'];
246
				}
247

    
248
				$gwifip = find_interface_ipv6_ll($gateway['interface'], true);
249

    
250
				if (get_ll_scope($gwifip) == '') {
251
					$gwifip .= '%' . $gateway['interface'];
252
				}
253
			} else {
254
				$gwifip = find_interface_ipv6($gateway['interface'], true);
255
			}
256

    
257
			if (!is_ipaddrv6($gwifip)) {
258
				continue; //Skip this target
259
			}
260

    
261
			/*
262
			 * If the gateway is the same as the monitor we do not add a
263
			 * route as this will break the routing table.
264
			 * Add static routes for each gateway with their monitor IP
265
			 * not strictly necessary but is a added level of protection.
266
			 */
267
			if ($gateway['gateway'] != $gateway['monitor']) {
268
				log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
269
				$route_to = "-host -inet6 {$gateway['monitor']}";
270
				if (interface_isppp_type($gateway['friendlyiface'])) {
271
					route_add_or_change("{$route_to} -iface {$gateway['interface']}");
272
				} else {
273
					route_add_or_change("{$route_to} {$gateway['gateway']}");
274
				}
275

    
276
				pfSense_kill_states("::0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmpv6");
277
			}
278
		} else {
279
			continue;
280
		}
281

    
282
		$monitor_ips[] = $gateway['monitor'];
283
		$gateways_arr[$gwname]['enable_dpinger'] = true;
284
		$gateways_arr[$gwname]['gwifip'] = $gwifip;
285
	}
286

    
287
	stop_dpinger();
288

    
289
	/* Start new processes */
290
	foreach ($gateways_arr as $gateway) {
291
		if (!isset($gateway['enable_dpinger'])) {
292
			continue;
293
		}
294

    
295
		if (start_dpinger($gateway) != 0) {
296
			log_error(sprintf(gettext("Error starting gateway monitor for %s"), $gateway['name']));
297
		}
298
	}
299

    
300
	return;
301
}
302

    
303
function get_dpinger_status($gwname, $detailed = false) {
304
	global $g;
305

    
306
	$running_processes = running_dpinger_processes();
307

    
308
	if (!isset($running_processes[$gwname])) {
309
		log_error(sprintf(gettext('dpinger: No dpinger session running for gateway %s'), $gwname));
310
		return false;
311
	}
312

    
313
	$proc = $running_processes[$gwname];
314
	unset($running_processes);
315

    
316
	if (!file_exists($proc['socket'])) {
317
		log_error("dpinger: status socket {$proc['socket']} not found");
318
		return false;
319
	}
320

    
321
	$fp = stream_socket_client("unix://{$proc['socket']}", $errno, $errstr, 10);
322
	if (!$fp) {
323
		log_error(sprintf(gettext('dpinger: cannot connect to status socket %1$s - %2$s (%3$s)'), $proc['socket'], $errstr, $errno));
324
		return false;
325
	}
326

    
327
	$status = '';
328
	while (!feof($fp)) {
329
		$status .= fgets($fp, 1024);
330
	}
331
	fclose($fp);
332

    
333
	$r = array();
334
	list(
335
	    $r['gwname'],
336
	    $r['latency_avg'],
337
	    $r['latency_stddev'],
338
	    $r['loss']
339
	) = explode(' ', preg_replace('/\n/', '', $status));
340

    
341
	$r['srcip'] = $proc['srcip'];
342
	$r['targetip'] = $proc['targetip'];
343

    
344
	$gateways_arr = return_gateways_array();
345
	unset($gw);
346
	if (isset($gateways_arr[$gwname])) {
347
		$gw = $gateways_arr[$gwname];
348
	}
349

    
350
	$r['latency_avg'] = round($r['latency_avg']/1000, 3);
351
	$r['latency_stddev'] = round($r['latency_stddev']/1000, 3);
352

    
353
	$r['status'] = "none";
354
	if (isset($gw) && isset($gw['force_down'])) {
355
		$r['status'] = "force_down";
356
	} else if (isset($gw)) {
357
		$settings = return_dpinger_defaults();
358

    
359
		$keys = array(
360
		    'latencylow',
361
		    'latencyhigh',
362
		    'losslow',
363
		    'losshigh'
364
		);
365

    
366
		/* Replace default values by user-defined */
367
		foreach ($keys as $key) {
368
			if (isset($gw[$key]) && is_numeric($gw[$key])) {
369
				$settings[$key] = $gw[$key];
370
			}
371
		}
372

    
373
		if ($r['latency_avg'] > $settings['latencyhigh']) {
374
			if ($detailed) {
375
				$r['status'] = "highdelay";
376
			} else {
377
				$r['status'] = "down";
378
			}
379
		} else if ($r['loss'] > $settings['losshigh']) {
380
			if ($detailed) {
381
				$r['status'] = "highloss";
382
			} else {
383
				$r['status'] = "down";
384
			}
385
		} else if ($r['latency_avg'] > $settings['latencylow']) {
386
			$r['status'] = "delay";
387
		} else if ($r['loss'] > $settings['losslow']) {
388
			$r['status'] = "loss";
389
		}
390
	}
391

    
392
	return $r;
393
}
394

    
395
/* return the status of the dpinger targets as an array */
396
function return_gateways_status($byname = false) {
397
	global $config, $g;
398

    
399
	$dpinger_gws = running_dpinger_processes();
400
	$status = array();
401

    
402
	$gateways_arr = return_gateways_array();
403

    
404
	foreach ($dpinger_gws as $gwname => $gwdata) {
405
		// If action is disabled for this gateway, then we want a detailed status.
406
		// That reports "highdelay" or "highloss" rather than just "down".
407
		// Because reporting the gateway down would be misleading (gateway action is disabled)
408
		$detailed = $gateways_arr[$gwname]['action_disable'];
409
		$dpinger_status = get_dpinger_status($gwname, $detailed);
410
		if ($dpinger_status === false) {
411
			continue;
412
		}
413

    
414
		if ($byname == false) {
415
			$target = $dpinger_status['targetip'];
416
		} else {
417
			$target = $gwname;
418
		}
419

    
420
		$status[$target] = array();
421
		$status[$target]['monitorip'] = $dpinger_status['targetip'];
422
		$status[$target]['srcip'] = $dpinger_status['srcip'];
423
		$status[$target]['name'] = $gwname;
424
		$status[$target]['delay'] = empty($dpinger_status['latency_avg']) ? "0ms" : $dpinger_status['latency_avg'] . "ms";
425
		$status[$target]['stddev'] = empty($dpinger_status['latency_stddev']) ? "0ms" : $dpinger_status['latency_stddev'] . "ms";
426
		$status[$target]['loss'] = empty($dpinger_status['loss']) ? "0.0%" : round($dpinger_status['loss'], 1) . "%";
427
		$status[$target]['status'] = $dpinger_status['status'];
428
	}
429

    
430
	/* tack on any gateways that have monitoring disabled
431
	 * or are down, which could cause gateway groups to fail */
432
	$gateways_arr = return_gateways_array();
433
	foreach ($gateways_arr as $gwitem) {
434
		if (!isset($gwitem['monitor_disable'])) {
435
			continue;
436
		}
437
		if (!is_ipaddr($gwitem['monitor'])) {
438
			$realif = $gwitem['interface'];
439
			$tgtip = get_interface_gateway($realif);
440
			if (!is_ipaddr($tgtip)) {
441
				$tgtip = "none";
442
			}
443
			$srcip = find_interface_ip($realif);
444
		} else {
445
			$tgtip = $gwitem['monitor'];
446
			$srcip = find_interface_ip($realif);
447
		}
448
		if ($byname == true) {
449
			$target = $gwitem['name'];
450
		} else {
451
			$target = $tgtip;
452
		}
453

    
454
		/* failsafe for down interfaces */
455
		if ($target == "none") {
456
			$target = $gwitem['name'];
457
			$status[$target]['name'] = $gwitem['name'];
458
			$status[$target]['delay'] = "0.0ms";
459
			$status[$target]['loss'] = "100.0%";
460
			$status[$target]['status'] = "down";
461
		} else {
462
			$status[$target]['monitorip'] = $tgtip;
463
			$status[$target]['srcip'] = $srcip;
464
			$status[$target]['name'] = $gwitem['name'];
465
			$status[$target]['delay'] = "";
466
			$status[$target]['loss'] = "";
467
			$status[$target]['status'] = "none";
468
		}
469

    
470
		$status[$target]['monitor_disable'] = true;
471
	}
472
	return($status);
473
}
474

    
475
function return_gateways_status_text($byname = false, $brief = false) {
476
	$gwstat = return_gateways_status($byname);
477
	$output = "";
478
	$widths = array();
479
	$col_sep = 2;
480
	if ($brief) {
481
		$collist = array('status' => "Status");
482
	} else {
483
		$collist = array('monitorip' => "Monitor",
484
				'srcip' => "Source",
485
				'delay' => "Delay",
486
				'stddev' => "StdDev",
487
				'loss' => "Loss",
488
				'status' => "Status");
489
	}
490
	foreach ($gwstat as $gw) {
491
		foreach ($gw as $gwdidx => $gwdata) {
492
			if (strlen($gwdata) > $widths[$gwdidx]) {
493
				$widths[$gwdidx] = strlen($gwdata);
494
			}
495
		}
496
	}
497

    
498
	$output .= str_pad("Name", $widths['name'] + $col_sep, " ", STR_PAD_RIGHT);
499
	foreach ($collist as $hdrcol => $hdrdesc) {
500
		if (strlen($hdrdesc) > $widths[$hdrcol]) {
501
			$widths[$hdrcol] = strlen($hdrdesc);
502
		}
503
		$output .= str_pad($hdrdesc, $widths[$hdrcol] + $col_sep, " ", (substr($hdrcol, -2, 2) == "ip") ? STR_PAD_RIGHT : STR_PAD_LEFT);
504
	}
505
	$output .= "\n";
506

    
507
	foreach ($gwstat as $idx => $gw) {
508
		$output .= str_pad($gw['name'], $widths['name'] + $col_sep, " ", STR_PAD_RIGHT);
509
		foreach (array_keys($collist) as $col) {
510
			$output .= str_pad($gw[$col], $widths[$col] + $col_sep, " ", (substr($col, -2, 2) == "ip") ? STR_PAD_RIGHT : STR_PAD_LEFT);
511
		}
512
		$output .= "\n";
513
	}
514

    
515
	return $output;
516
}
517

    
518
/* Return all configured gateways on the system */
519
function return_gateways_array($disabled = false, $localhost = false, $inactive = false) {
520
	global $config, $g;
521

    
522
	$gateways_arr = array();
523
	$gateways_arr_temp = array();
524

    
525
	$found_defaultv4 = 0;
526
	$found_defaultv6 = 0;
527

    
528
	// Ensure the interface cache is up to date first
529
	$interfaces = get_interface_arr(true);
530

    
531
	$i = -1;
532
	/* Process/add all the configured gateways. */
533
	if (is_array($config['gateways']['gateway_item'])) {
534
		foreach ($config['gateways']['gateway_item'] as $gateway) {
535
			/* Increment it here to do not skip items */
536
			$i++;
537

    
538
			if (empty($config['interfaces'][$gateway['interface']])) {
539
				if ($inactive === false) {
540
					continue;
541
				} else {
542
					$gateway['inactive'] = true;
543
				}
544
			}
545
			$wancfg = $config['interfaces'][$gateway['interface']];
546

    
547
			/* skip disabled interfaces */
548
			if ($disabled === false && (!isset($wancfg['enable']))) {
549
				continue;
550
			}
551

    
552
			/* if the gateway is dynamic and we can find the IPv4, Great! */
553
			if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") {
554
				if ($gateway['ipprotocol'] == "inet") {
555
					/* we know which interfaces is dynamic, this should be made a function */
556
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
557
					/* no IP address found, set to dynamic */
558
					if (!is_ipaddrv4($gateway['gateway'])) {
559
						$gateway['gateway'] = "dynamic";
560
					}
561
					$gateway['dynamic'] = true;
562
				}
563

    
564
				/* if the gateway is dynamic and we can find the IPv6, Great! */
565
				else if ($gateway['ipprotocol'] == "inet6") {
566
					/* we know which interfaces is dynamic, this should be made a function, and for v6 too */
567
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
568
					/* no IPv6 address found, set to dynamic */
569
					if (!is_ipaddrv6($gateway['gateway'])) {
570
						$gateway['gateway'] = "dynamic";
571
					}
572
					$gateway['dynamic'] = true;
573
				}
574
			} else {
575
				/* getting this detection right is hard at this point because we still don't
576
				 * store the address family in the gateway item */
577
				if (is_ipaddrv4($gateway['gateway'])) {
578
					$gateway['ipprotocol'] = "inet";
579
				} else if (is_ipaddrv6($gateway['gateway'])) {
580
					$gateway['ipprotocol'] = "inet6";
581
				}
582
			}
583

    
584
			if (isset($gateway['monitor_disable'])) {
585
				$gateway['monitor_disable'] = true;
586
			} else if (empty($gateway['monitor'])) {
587
				$gateway['monitor'] = $gateway['gateway'];
588
			}
589

    
590
			if (isset($gateway['action_disable'])) {
591
				$gateway['action_disable'] = true;
592
			}
593

    
594
			$gateway['friendlyiface'] = $gateway['interface'];
595

    
596
			/* special treatment for tunnel interfaces */
597
			if ($gateway['ipprotocol'] == "inet6") {
598
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet6", false, false);
599
			} else {
600
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet", false, false);
601
			}
602

    
603
			/* entry has a default flag, use it */
604
			if (isset($gateway['defaultgw'])) {
605
				if ($gateway['ipprotocol'] == "inet") {
606
					$gateway['defaultgw'] = true;
607
					$found_defaultv4 = 1;
608
				} else if ($gateway['ipprotocol'] == "inet6") {
609
					$gateway['defaultgw'] = true;
610
					$found_defaultv6 = 1;
611
				}
612
			}
613
			/* include the gateway index as the attribute */
614
			$gateway['attribute'] = $i;
615

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

    
620
			/* skip disabled gateways if the caller has not asked for them to be returned. */
621
			if (!($disabled === false && isset($gateway['disabled']))) {
622
				$gateways_arr[$gateway['name']] = $gateway;
623
			}
624
		}
625
	}
626
	unset($gateway);
627

    
628
	/* Loop through all interfaces with a gateway and add it to a array */
629
	if ($disabled == false) {
630
		$iflist = get_configured_interface_with_descr();
631
	} else {
632
		$iflist = get_configured_interface_with_descr(false, true);
633
	}
634

    
635
	/* Process/add dynamic v4 gateways. */
636
	foreach ($iflist as $ifname => $friendly) {
637
		if (!interface_has_gateway($ifname)) {
638
			continue;
639
		}
640

    
641
		if (empty($config['interfaces'][$ifname])) {
642
			continue;
643
		}
644

    
645
		$ifcfg = &$config['interfaces'][$ifname];
646
		if (!isset($ifcfg['enable'])) {
647
			continue;
648
		}
649

    
650
		if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) {
651
			continue;
652
		}
653

    
654
		$ctype = "";
655
		switch ($ifcfg['ipaddr']) {
656
			case "dhcp":
657
			case "pppoe":
658
			case "l2tp":
659
			case "pptp":
660
			case "ppp":
661
				$ctype = strtoupper($ifcfg['ipaddr']);
662
				break;
663
			default:
664
				$tunnelif = substr($ifcfg['if'], 0, 3);
665
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
666
					// if current iface is an ovpn server endpoint then check its type, skip tap only
667
					if (substr($ifcfg['if'], 4, 1) == 's') {
668
						$ovpnid = substr($ifcfg['if'], 5);
669
						if (is_array($config['openvpn']['openvpn-server'])) {
670
							foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) {
671
								if ($ovpnserverconf['vpnid'] == $ovpnid) {
672
									if ($ovpnserverconf['dev_mode'] == "tap") {
673
										continue 3;
674
									}
675
								}
676
							}
677
						}
678
					}
679
					$ctype = "VPNv4";
680
				} else if ($tunnelif == "gif" || $tunnelif == "gre") {
681
					$ctype = "TUNNELv4";
682
				}
683
				break;
684
		}
685
		$ctype = "_". strtoupper($ctype);
686

    
687
		$gateway = array();
688
		$gateway['dynamic'] = false;
689
		$gateway['ipprotocol'] = "inet";
690
		$gateway['gateway'] = get_interface_gateway($ifname, $gateway['dynamic']);
691
		$gateway['interface'] = get_real_interface($ifname);
692
		$gateway['friendlyiface'] = $ifname;
693
		$gateway['name'] = "{$friendly}{$ctype}";
694
		$gateway['attribute'] = "system";
695

    
696
		if (($gateway['dynamic'] === "default") && ($found_defaultv4 == 0)) {
697
			$gateway['defaultgw'] = true;
698
			$gateway['dynamic'] = true;
699
			$found_defaultv4 = 1;
700
		}
701
		/* Loopback dummy for dynamic interfaces without a IP */
702
		if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) {
703
			$gateway['gateway'] = "dynamic";
704
		}
705

    
706
		/* automatically skip known static and dynamic gateways that were previously processed */
707
		foreach ($gateways_arr_temp as $gateway_item) {
708
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
709
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
710
				continue 2;
711
			}
712
		}
713

    
714
		if (is_ipaddrv4($gateway['gateway'])) {
715
			$gateway['monitor'] = $gateway['gateway'];
716
		}
717

    
718
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
719
		$gateways_arr[$gateway['name']] = $gateway;
720
	}
721
	unset($gateway);
722

    
723
	/* Process/add dynamic v6 gateways. */
724
	foreach ($iflist as $ifname => $friendly) {
725
		/* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */
726
		if (!isset($config['system']['ipv6allow'])) {
727
			break;
728
		}
729

    
730
		if (!interface_has_gatewayv6($ifname)) {
731
			continue;
732
		}
733

    
734
		if (empty($config['interfaces'][$ifname])) {
735
			continue;
736
		}
737

    
738
		$ifcfg = &$config['interfaces'][$ifname];
739
		if (!isset($ifcfg['enable'])) {
740
			continue;
741
		}
742

    
743
		if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) {
744
			continue;
745
		}
746

    
747
		$ctype = "";
748
		switch ($ifcfg['ipaddrv6']) {
749
			case "slaac":
750
			case "dhcp6":
751
			case "6to4":
752
			case "6rd":
753
				$ctype = strtoupper($ifcfg['ipaddrv6']);
754
				break;
755
			default:
756
				$tunnelif = substr($ifcfg['if'], 0, 3);
757
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
758
					// if current iface is an ovpn server endpoint then check its type, skip tap only
759
					if (substr($ifcfg['if'], 4, 1) == 's') {
760
						$ovpnid = substr($ifcfg['if'], 5);
761
						if (is_array($config['openvpn']['openvpn-server'])) {
762
							foreach ($config['openvpn']['openvpn-server'] as & $ovpnserverconf) {
763
								if ($ovpnserverconf['vpnid'] == $ovpnid) {
764
									if ($ovpnserverconf['dev_mode'] == "tap") {
765
										continue 3;
766
									}
767
								}
768
							}
769
						}
770
					}
771
					$ctype = "VPNv6";
772
				} else if ($tunnelif == "gif" || $tunnelif == "gre") {
773
					$ctype = "TUNNELv6";
774
				}
775
				break;
776
		}
777
		$ctype = "_". strtoupper($ctype);
778

    
779
		$gateway = array();
780
		$gateway['dynamic'] = false;
781
		$gateway['ipprotocol'] = "inet6";
782
		$gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']);
783
		$gateway['interface'] = get_real_interface($ifname, "inet6");
784
		switch ($ifcfg['ipaddrv6']) {
785
			case "6rd":
786
			case "6to4":
787
				$gateway['dynamic'] = "default";
788
				break;
789
		}
790
		$gateway['friendlyiface'] = $ifname;
791
		$gateway['name'] = "{$friendly}{$ctype}";
792
		$gateway['attribute'] = "system";
793

    
794
		if (($gateway['dynamic'] === "default") && ($found_defaultv6 == 0)) {
795
			$gateway['defaultgw'] = true;
796
			$gateway['dynamic'] = true;
797
			$found_defaultv6 = 1;
798
		}
799

    
800
		/* Loopback dummy for dynamic interfaces without a IP */
801
		if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) {
802
			$gateway['gateway'] = "dynamic";
803
		}
804

    
805
		/* automatically skip known static and dynamic gateways that were previously processed */
806
		foreach ($gateways_arr_temp as $gateway_item) {
807
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
808
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
809
				continue 2;
810
			}
811
		}
812

    
813
		if (is_ipaddrv6($gateway['gateway'])) {
814
			$gateway['monitor'] = $gateway['gateway'];
815
		}
816

    
817
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
818
		$gateways_arr[$gateway['name']] = $gateway;
819
	}
820
	unset($gateway);
821

    
822
	/* FIXME: Should this be enabled.
823
	 * Some interface like wan might be default but have no info recorded
824
	 * the config. */
825
	/* this is a fallback if all else fails and we want to get packets out @smos */
826
	if ($found_defaultv4 == 0 || $found_defaultv6 == 0) {
827
		foreach ($gateways_arr as &$gateway) {
828
			if (($gateway['friendlyiface'] == "wan") && ($found_defaultv4 == 0) && (!isset($gateway['ipprotocol']) || ($gateway['ipprotocol'] == "inet"))) {
829
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgw")) {
830
					$gateway['defaultgw'] = true;
831
					$found_defaultv4 = 1;
832
				}
833
			}
834
			else if (($gateway['friendlyiface'] == "wan") && ($found_defaultv6 == 0) && ($gateway['ipprotocol'] == "inet6")) {
835
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgwv6")) {
836
					$gateway['defaultgw'] = true;
837
					$found_defaultv6 = 1;
838
				}
839
			}
840
		}
841
	}
842

    
843
	if ($localhost === true) {
844
		/* attach localhost for Null routes */
845
		$gwlo4 = array();
846
		$gwlo4['name'] = "Null4";
847
		$gwlo4['interface'] = "lo0";
848
		$gwlo4['ipprotocol'] = "inet";
849
		$gwlo4['gateway'] = "127.0.0.1";
850
		$gwlo6 = array();
851
		$gwlo6['name'] = "Null6";
852
		$gwlo6['interface'] = "lo0";
853
		$gwlo6['ipprotocol'] = "inet6";
854
		$gwlo6['gateway'] = "::1";
855
		$gateways_arr['Null4'] = $gwlo4;
856
		$gateways_arr['Null6'] = $gwlo6;
857
	}
858
	return($gateways_arr);
859
}
860

    
861
function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
862
	global $config, $g;
863
	/*
864
	 * NOTE: The code below is meant to replace the default gateway when it goes down.
865
	 *	This facilitates services running on pfSense itself and are not handled by a PBR to continue working.
866
	 */
867
	$upgw = '';
868
	$dfltgwname = '';
869
	$dfltgwdown = false;
870
	$dfltgwfound = false;
871
	foreach ($gateways_arr as $gwname => $gwsttng) {
872
		if (($gwsttng['ipprotocol'] == $ipprotocol) && isset($gwsttng['defaultgw'])) {
873
			$dfltgwfound = true;
874
			$dfltgwname = $gwname;
875
			if (!isset($gwsttng['monitor_disable']) && !isset($gwsttng['action_disable']) && $gateways_status[$gwname]['status'] != "none") {
876
				$dfltgwdown = true;
877
			}
878
		}
879
		/* Keep a record of the last up gateway */
880
		/* XXX: Blacklist lan for now since it might cause issues to those who have a gateway set for it */
881
		if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) && (isset($gwsttng['monitor_disable']) || isset($gwsttng['action_disable']) || $gateways_status[$gwname]['status'] == "none") && $gwsttng[$gwname]['friendlyiface'] != "lan") {
882
			$upgw = $gwname;
883
		}
884
		if ($dfltgwdown == true && !empty($upgw)) {
885
			break;
886
		}
887
	}
888
	if ($dfltgwfound == false) {
889
		$gwname = convert_friendly_interface_to_friendly_descr("wan");
890
		if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down")) {
891
			$dfltgwdown = true;
892
		}
893
	}
894
	if ($dfltgwdown == true && !empty($upgw)) {
895
		if ($gateways_arr[$upgw]['gateway'] == "dynamic") {
896
			$gateways_arr[$upgw]['gateway'] = get_interface_gateway($gateways_arr[$upgw]['friendlyiface']);
897
		}
898
		if (is_ipaddr($gateways_arr[$upgw]['gateway'])) {
899
			log_error("Default gateway down setting {$upgw} as default!");
900
			if (is_ipaddrv6($gateways_arr[$upgw]['gateway'])) {
901
				$inetfamily = "-inet6";
902
				if (is_linklocal($gateways_arr[$upgw]['gateway']) && get_ll_scope($gateways_arr[$upgw]['gateway']) == '') {
903
					$gateways_arr[$upgw]['gateway'] .= "%" . $gateways_arr[$upgw]['interface'];
904
				}
905
			} else {
906
				$inetfamily = "-inet";
907
			}
908
			route_add_or_change("{$inetfamily} default {$gateways_arr[$upgw]['gateway']}");
909
		}
910
	} else if (!empty($dfltgwname)) {
911
		$defaultgw = trim(exec("/sbin/route -n get -{$ipprotocol} default | /usr/bin/awk '/gateway:/ {print $2}'"), " \n");
912
		if ($ipprotocol == 'inet6' && !is_ipaddrv6($gateways_arr[$dfltgwname]['gateway'])) {
913
			return;
914
		}
915
		if ($ipprotocol == 'inet' && !is_ipaddrv4($gateways_arr[$dfltgwname]['gateway'])) {
916
			return;
917
		}
918
		if ($ipprotocol == 'inet6') {
919
			if (is_linklocal($gateways_arr[$upgw]['gateway']) && get_ll_scope($gateways_arr[$upgw]['gateway']) == '') {
920
				$gateways_arr[$upgw]['gateway'] .= "%" . $gateways_arr[$upgw]['interface'];
921
			}
922
			if (is_linklocal($gateways_arr[$dfltgwname]['gateway']) && get_ll_scope($gateways_arr[$dfltgwname]['gateway']) == '') {
923
				$gateways_arr[$dfltgwname]['gateway'] .= "%" . $gateways_arr[$dfltgwname]['interface'];
924
			}
925
		}
926
		if ($defaultgw != $gateways_arr[$dfltgwname]['gateway']) {
927
			route_add_or_change("-{$ipprotocol} default {$gateways_arr[$dfltgwname]['gateway']}");
928
		}
929
	}
930
}
931

    
932
/*
933
 * Return an array with all gateway groups with name as key
934
 * All gateway groups will be processed before returning the array.
935
 */
936
function return_gateway_groups_array() {
937
	global $config, $g;
938

    
939
	/* fetch the current gateways status */
940
	$gateways_status = return_gateways_status(true);
941
	$gateways_arr = return_gateways_array();
942
	$gateway_groups_array = array();
943

    
944
	if (isset($config['system']['gw_switch_default'])) {
945
		fixup_default_gateway("inet", $gateways_status, $gateways_arr);
946
		fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
947
	}
948
	if (is_array($config['gateways']['gateway_group'])) {
949
		$viplist = get_configured_vip_list();
950
		foreach ($config['gateways']['gateway_group'] as $group) {
951
			$gateway_groups_array[$group['name']]['descr'] = $group['descr'];
952
			/* create array with group gateways members separated by tier */
953
			$tiers = array();
954
			$backupplan = array();
955
			$gwvip_arr = array();
956
			foreach ($group['item'] as $item) {
957
				list($gwname, $tier, $vipname) = explode("|", $item);
958

    
959
				if (is_ipaddr($viplist[$vipname])) {
960
					if (!is_array($gwvip_arr[$group['name']])) {
961
						$gwvip_arr[$group['name']] = array();
962
					}
963
					$gwvip_arr[$group['name']][$gwname] = $vipname;
964
				}
965

    
966
				/* Do it here rather than reiterating again the group in case no member is up. */
967
				if (!is_array($backupplan[$tier])) {
968
					$backupplan[$tier] = array();
969
				}
970
				$backupplan[$tier][] = $gwname;
971

    
972
				/* check if the gateway is available before adding it to the array */
973
				if (is_array($gateways_status[$gwname])) {
974
					$status = $gateways_status[$gwname];
975
					$gwdown = false;
976
					if (stristr($status['status'], "down")) {
977
						$msg = sprintf(gettext('MONITOR: %1$s is down, omitting from routing group %2$s'), $gwname, $group['name']);
978
						$gwdown = true;
979
					} else if (stristr($status['status'], "loss") && strstr($group['trigger'], "loss")) {
980
						/* packet loss */
981
						$msg = sprintf(gettext('MONITOR: %1$s has packet loss, omitting from routing group %2$s'), $gwname, $group['name']);
982
						$gwdown = true;
983
					} else if (stristr($status['status'], "delay") && strstr($group['trigger'] , "latency")) {
984
						/* high latency */
985
						$msg = sprintf(gettext('MONITOR: %1$s has high latency, omitting from routing group %2$s'), $gwname, $group['name']);
986
						$gwdown = true;
987
					}
988
					$pluginparams = array();
989
					$pluginparams['type'] = 'gateway';
990
					$pluginparams['name'] = ${gwname};
991
					if ($gwdown == true) {
992
						$pluginparams['event'] = 'gateway.down';
993
						if (!file_exists("/tmp/.down.{$gwname}")) {
994
							$msg .= "\n".implode("|", $status);
995
							touch("/tmp/.down.{$gwname}");
996
							log_error($msg);
997
							notify_via_growl($msg);
998
							notify_via_smtp($msg);
999
						}
1000
					} else {
1001
						$pluginparams['event'] = 'gateway.up';
1002
						/* Online add member */
1003
						if (!is_array($tiers[$tier])) {
1004
							$tiers[$tier] = array();
1005
						}
1006
						$tiers[$tier][] = $gwname;
1007
						if (unlink_if_exists("/tmp/.down.{$gwname}")) {
1008
							$msg = sprintf(gettext('MONITOR: %1$s is available now, adding to routing group %2$s'), $gwname, $group['name']);
1009
							$msg .= "\n".implode("|", $status);
1010
							log_error($msg);
1011
							notify_via_growl($msg);
1012
							notify_via_smtp($msg);
1013
						}
1014
					}
1015
					if (isset($gateways_arr[$gwname]['interface']))
1016
						$pluginparams['interface'] = $gateways_arr[$gwname]['interface'];
1017
					pkg_call_plugins('plugin_gateway', $pluginparams);
1018
				} else if (isset($gateways_arr[$gwname]['monitor_disable']) || isset($gateways_arr[$gwname]['action_disable'])) {
1019
					$tiers[$tier][] = $gwname;
1020
				}
1021
			}
1022
			$tiers_count = count($tiers);
1023
			if ($tiers_count == 0) {
1024
				/* Oh dear, we have no members! Engage Plan B */
1025
				if (!platform_booting()) {
1026
					$msg = sprintf(gettext('Gateways status could not be determined, considering all as up/active. (Group: %s)'), $group['name']);
1027
					log_error($msg);
1028
					notify_via_growl($msg);
1029
					//notify_via_smtp($msg);
1030
				}
1031
				$tiers = $backupplan;
1032
			}
1033
			/* sort the tiers array by the tier key */
1034
			ksort($tiers);
1035

    
1036
			/* we do not really foreach the tiers as we stop after the first tier */
1037
			foreach ($tiers as $tieridx => $tier) {
1038
				/* process all gateways in this tier */
1039
				foreach ($tier as $member) {
1040
					/* determine interface gateway */
1041
					if (isset($gateways_arr[$member])) {
1042
						$gateway = $gateways_arr[$member];
1043
						$int = $gateway['interface'];
1044
						$gatewayip = "";
1045
						if (is_ipaddr($gateway['gateway'])) {
1046
							$gatewayip = $gateway['gateway'];
1047
						} else if (!empty($int)) {
1048
							$gatewayip = get_interface_gateway($gateway['friendlyiface']);
1049
						}
1050

    
1051
						if (!empty($int)) {
1052
							$gateway_groups_array[$group['name']]['ipprotocol'] = $gateway['ipprotocol'];
1053
							if (is_ipaddr($gatewayip)) {
1054
								$groupmember = array();
1055
								$groupmember['int'] = $int;
1056
								$groupmember['gwip'] = $gatewayip;
1057
								$groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1;
1058
								if (is_array($gwvip_arr[$group['name']]) && !empty($gwvip_arr[$group['name']][$member]))
1059
									$groupmember['vip'] = $gwvip_arr[$group['name']][$member];
1060
								$gateway_groups_array[$group['name']][] = $groupmember;
1061
							}
1062
						}
1063
					}
1064
				}
1065
				/* we should have the 1st available tier now, exit stage left */
1066
				if (count($gateway_groups_array[$group['name']]) > 0) {
1067
					break;
1068
				} else {
1069
					log_error(sprintf(gettext('GATEWAYS: Group %1$s did not have any gateways up on tier %2$s!'), $group['name'], $tieridx));
1070
				}
1071
			}
1072
		}
1073
	}
1074

    
1075
	return ($gateway_groups_array);
1076
}
1077

    
1078
/* Update DHCP WAN Interface ip address in gateway group item */
1079
function dhclient_update_gateway_groups_defaultroute($interface = "wan") {
1080
	global $config, $g;
1081
	foreach ($config['gateways']['gateway_item'] as & $gw) {
1082
		if ($gw['interface'] == $interface) {
1083
			$current_gw = get_interface_gateway($interface);
1084
			if ($gw['gateway'] <> $current_gw) {
1085
				$gw['gateway'] = $current_gw;
1086
				$changed = true;
1087
			}
1088
		}
1089
	}
1090
	if ($changed && $current_gw) {
1091
		write_config(sprintf(gettext('Updating gateway group gateway for %1$s - new gateway is %2$s'), $interface, $current_gw));
1092
	}
1093
}
1094

    
1095
function lookup_gateway_ip_by_name($name, $disabled = false) {
1096

    
1097
	$gateways_arr = return_gateways_array($disabled, true);
1098
	foreach ($gateways_arr as $gname => $gw) {
1099
		if ($gw['name'] === $name || $gname === $name) {
1100
			return $gw['gateway'];
1101
		}
1102
	}
1103

    
1104
	return false;
1105
}
1106

    
1107
function lookup_gateway_monitor_ip_by_name($name) {
1108

    
1109
	$gateways_arr = return_gateways_array(false, true);
1110
	if (!empty($gateways_arr[$name])) {
1111
		$gateway = $gateways_arr[$name];
1112
		if (!is_ipaddr($gateway['monitor'])) {
1113
			return $gateway['gateway'];
1114
		}
1115

    
1116
		return $gateway['monitor'];
1117
	}
1118

    
1119
	return (false);
1120
}
1121

    
1122
function lookup_gateway_interface_by_name($name) {
1123

    
1124
	$gateways_arr = return_gateways_array(false, true);
1125
	if (!empty($gateways_arr[$name])) {
1126
		$interfacegw = $gateways_arr[$name]['friendlyiface'];
1127
		return ($interfacegw);
1128
	}
1129

    
1130
	return (false);
1131
}
1132

    
1133
function get_interface_gateway($interface, &$dynamic = false) {
1134
	global $config, $g;
1135

    
1136
	if (substr($interface, 0, 4) == '_vip') {
1137
		$interface = get_configured_vip_interface($interface);
1138
		if (substr($interface, 0, 4) == '_vip') {
1139
			$interface = get_configured_vip_interface($interface);
1140
		}
1141
	}
1142

    
1143
	$gw = NULL;
1144
	$gwcfg = $config['interfaces'][$interface];
1145
	if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) {
1146
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1147
			if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
1148
				$gw = $gateway['gateway'];
1149
				break;
1150
			}
1151
		}
1152
	}
1153

    
1154
	// for dynamic interfaces we handle them through the $interface_router file.
1155
	if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) {
1156
		$realif = get_real_interface($interface);
1157
		if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
1158
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
1159
			$dynamic = true;
1160
		}
1161
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) {
1162
			$dynamic = "default";
1163
		}
1164

    
1165
	}
1166

    
1167
	/* return gateway */
1168
	return ($gw);
1169
}
1170

    
1171
function get_interface_gateway_v6($interface, &$dynamic = false) {
1172
	global $config, $g;
1173

    
1174
	if (substr($interface, 0, 4) == '_vip') {
1175
		$interface = get_configured_vip_interface($interface);
1176
		if (substr($interface, 0, 4) == '_vip') {
1177
			$interface = get_configured_vip_interface($interface);
1178
		}
1179
	}
1180

    
1181
	$gw = NULL;
1182
	$gwcfg = $config['interfaces'][$interface];
1183
	if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) {
1184
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1185
			if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
1186
				$gw = $gateway['gateway'];
1187
				break;
1188
			}
1189
		}
1190
	}
1191

    
1192
	// for dynamic interfaces we handle them through the $interface_router file.
1193
	if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) {
1194
		$realif = get_real_interface($interface);
1195
		if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
1196
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
1197
			$dynamic = true;
1198
		}
1199
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) {
1200
			$dynamic = "default";
1201
		}
1202
	}
1203
	/* return gateway */
1204
	return ($gw);
1205
}
1206

    
1207
/* Check a IP address against a gateway IP or name
1208
 * to verify it's address family */
1209
function validate_address_family($ipaddr, $gwname, $disabled = false) {
1210
	$v4ip = false;
1211
	$v6ip = false;
1212
	$v4gw = false;
1213
	$v6gw = false;
1214

    
1215
	if (is_ipaddrv4($ipaddr)) {
1216
		$v4ip = true;
1217
	}
1218
	if (is_ipaddrv6($ipaddr)) {
1219
		$v6ip = true;
1220
	}
1221
	if (is_ipaddrv4($gwname)) {
1222
		$v4gw = true;
1223
	}
1224
	if (is_ipaddrv6($gwname)) {
1225
		$v6gw = true;
1226
	}
1227

    
1228
	if ($v4ip && $v4gw) {
1229
		return true;
1230
	}
1231
	if ($v6ip && $v6gw) {
1232
		return true;
1233
	}
1234

    
1235
	/* still no match, carry on, lookup gateways */
1236
	if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname, $disabled))) {
1237
		$v4gw = true;
1238
	}
1239
	if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname, $disabled))) {
1240
		$v6gw = true;
1241
	}
1242

    
1243
	$gw_array = return_gateways_array();
1244
	if (is_array($gw_array[$gwname])) {
1245
		switch ($gw_array[$gwname]['ipprotocol']) {
1246
			case "inet":
1247
				$v4gw = true;
1248
				break;
1249
			case "inet6":
1250
				$v6gw = true;
1251
				break;
1252
		}
1253
	}
1254

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

    
1262
	return false;
1263
}
1264

    
1265
/* check if a interface is part of a gateway group */
1266
function interface_gateway_group_member($interface) {
1267
	global $config;
1268

    
1269
	if (is_array($config['gateways']['gateway_group'])) {
1270
		$groups = $config['gateways']['gateway_group'];
1271
	} else {
1272
		return false;
1273
	}
1274

    
1275
	$gateways_arr = return_gateways_array(false, true);
1276
	foreach ($groups as $group) {
1277
		if (is_array($group['item'])) {
1278
			foreach ($group['item'] as $item) {
1279
				$elements = explode("|", $item);
1280
				$gwname = $elements[0];
1281
				if ($interface == $gateways_arr[$gwname]['interface']) {
1282
					unset($gateways_arr);
1283
					return true;
1284
				}
1285
			}
1286
		}
1287
	}
1288
	unset($gateways_arr);
1289

    
1290
	return false;
1291
}
1292

    
1293
function gateway_is_gwgroup_member($name) {
1294
	global $config;
1295

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

    
1302
	$members = array();
1303
	foreach ($groups as $group) {
1304
		if (is_array($group['item'])) {
1305
			foreach ($group['item'] as $item) {
1306
				$elements = explode("|", $item);
1307
				$gwname = $elements[0];
1308
				if ($name == $elements[0]) {
1309
					$members[] = $group['name'];
1310
				}
1311
			}
1312
		}
1313
	}
1314

    
1315
	return $members;
1316
}
1317
?>
(17-17/51)