Project

General

Profile

Download (73.5 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-2013 BSD Perimeter
8
 * Copyright (c) 2013-2016 Electric Sheep Fencing
9
 * Copyright (c) 2014-2021 Rubicon Communications, LLC (Netgate)
10
 * All rights reserved.
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 * http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24

    
25
require_once("config.inc");
26
require_once("rrd.inc");
27
require_once("ipsec.inc");
28
require_once("interfaces.inc");
29

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

    
44
function running_dpinger_processes() {
45
	global $g;
46

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

    
49
	$result = array();
50
	if ($pidfiles === FALSE) {
51
		return $result;
52
	}
53

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

    
69
	return $result;
70
}
71

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

    
80
	$running_processes = running_dpinger_processes();
81

    
82
	foreach ($running_processes as $running_gwname => $process) {
83
		if ($gwname != '' && $running_gwname != $gwname) {
84
			continue;
85
		}
86

    
87
		if (isvalidpid($process['pidfile'])) {
88
			killbypid($process['pidfile'], 3);
89
		} else {
90
			@unlink($process['pidfile']);
91
		}
92
	}
93
}
94

    
95
function start_dpinger($gateway) {
96
	global $g;
97

    
98
	if (!isset($gateway['gwifip'])) {
99
		return (false);
100
	}
101

    
102
	$dpinger_defaults = return_dpinger_defaults();
103

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

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

    
126
	$params .= "-d " .
127
	    (isset($gateway['data_payload']) && is_numeric($gateway['data_payload'])
128
	    ? $gateway['data_payload']
129
	    : $dpinger_defaults['data_payload']
130
	    ) . " ";
131

    
132
	$params .= "-s " .
133
	    (isset($gateway['interval']) && is_numeric($gateway['interval'])
134
	    ? $gateway['interval']
135
	    : $dpinger_defaults['interval']
136
	    ) . " ";
137

    
138
	$params .= "-l " .
139
	    (isset($gateway['loss_interval']) && is_numeric($gateway['loss_interval'])
140
	    ?  $gateway['loss_interval']
141
	    : $dpinger_defaults['loss_interval']
142
	    ) . " ";
143

    
144
	$params .= "-t " .
145
	    (isset($gateway['time_period']) && is_numeric($gateway['time_period'])
146
	    ?  $gateway['time_period']
147
	    : $dpinger_defaults['time_period']
148
	    ) . " ";
149

    
150
	$params .= "-A " .
151
	    (isset($gateway['alert_interval']) && is_numeric($gateway['alert_interval'])
152
	    ?  $gateway['alert_interval']
153
	    : $dpinger_defaults['alert_interval']
154
	    ) . " ";
155

    
156
	$params .= "-D " .
157
	    (isset($gateway['latencyhigh']) && is_numeric($gateway['latencyhigh'])
158
	    ?  $gateway['latencyhigh']
159
	    : $dpinger_defaults['latencyhigh']
160
	    ) . " ";
161

    
162
	$params .= "-L " .
163
	    (isset($gateway['losshigh']) && is_numeric($gateway['losshigh'])
164
	    ?  $gateway['losshigh']
165
	    : $dpinger_defaults['losshigh']
166
	    ) . " ";
167

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

    
171
	/* Do not try to bind IPv6 where interface is in tentative state */
172
	if (is_ipaddrv6($gateway['gwifip'])) {
173
		$err = interface_wait_tentative(get_real_interface(
174
		    $gateway['interface']));
175
		if ($err == false) {
176
			log_error(gettext("Timeout waiting for IPv6 address in tentative state.  dpinger will not run."));
177
			return (false);
178
		}
179
	}
180

    
181
	/* Redirect stdout to /dev/null to avoid exec() to wait for dpinger */
182
	return mwexec("/usr/local/bin/dpinger {$params} {$gateway['monitor']} >/dev/null");
183
}
184

    
185
/*
186
 * Starts dpinger processes and adds appropriate static routes for monitor IPs
187
 */
188
function setup_gateways_monitor() {
189
	global $config, $g;
190

    
191
	$gateways_arr = return_gateways_array();
192
	if (!is_array($gateways_arr)) {
193
		log_error(gettext("No gateways to monitor. dpinger will not run."));
194
		stop_dpinger();
195
		return;
196
	}
197

    
198
	$monitor_ips = array();
199
	foreach ($gateways_arr as $gwname => $gateway) {
200
		/* Do not monitor if such was requested */
201
		if (isset($gateway['monitor_disable'])) {
202
			continue;
203
		}
204
		if (empty($gateway['monitor']) || !is_ipaddr($gateway['monitor'])) {
205
			if (is_ipaddr($gateway['gateway'])) {
206
				$gateways_arr[$gwname]['monitor'] = $gateway['gateway'];
207
			} else { /* No chance to get an ip to monitor skip target. */
208
				continue;
209
			}
210
		}
211

    
212
		/* if the monitor address is already used before, skip */
213
		if (in_array($gateway['monitor'], $monitor_ips)) {
214
			continue;
215
		}
216

    
217
		/* Interface ip is needed since dpinger will bind a socket to it.
218
		 * However the config GUI should already have checked this and when
219
		 * PPPoE is used the IP address is set to "dynamic". So using is_ipaddrv4
220
		 * or is_ipaddrv6 to identify packet type would be wrong, especially as
221
		 * further checks (that can cope with the "dynamic" case) are present inside
222
		 * the if block. So using $gateway['ipprotocol'] is the better option.
223
		 */
224
		if ($gateway['ipprotocol'] == "inet") { // This is an IPv4 gateway...
225
			$gwifip = find_interface_ip($gateway['interface'], true);
226
			if (!is_ipaddrv4($gwifip)) {
227
				continue; //Skip this target
228
			}
229

    
230
			if ($gwifip == "0.0.0.0") {
231
				continue; //Skip this target - the gateway is still waiting for DHCP
232
			}
233

    
234
			/*
235
			 * If the gateway is the same as the monitor we do not add a
236
			 * route as this will break the routing table.
237
			 * Add static routes for each gateway with their monitor IP
238
			 * not strictly necessary but is a added level of protection.
239
			 */
240
			if (is_ipaddrv4($gateway['gateway']) && $gateway['monitor'] != $gateway['gateway']) {
241
				log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
242
				if (interface_isppp_type($gateway['friendlyiface'])) {
243
					route_add_or_change($gateway['monitor'],
244
					    '', $gateway['interface']);
245
					system_staticroutes_configure($gateway['friendlyiface']);
246
				} else {
247
					route_add_or_change($gateway['monitor'],
248
					    $gateway['gateway']);
249
				}
250

    
251
				pfSense_kill_states("0.0.0.0/0", utf8_encode($gateway['monitor']), utf8_encode($gateway['interface']), "icmp");
252
			}
253
		} else if ($gateway['ipprotocol'] == "inet6") { // This is an IPv6 gateway...
254
			if (is_linklocal($gateway['gateway']) &&
255
			    get_ll_scope($gateway['gateway']) == '') {
256
				$gateway['gateway'] .= '%' . $gateway['interface'];
257
			}
258

    
259
			if (is_linklocal($gateway['monitor'])) {
260
				if (get_ll_scope($gateway['monitor']) == '') {
261
					$gateways_arr[$gwname]['monitor'] .= '%' . $gateway['interface'];
262
				}
263

    
264
				$gwifip = find_interface_ipv6_ll($gateway['interface'], true);
265

    
266
				if (get_ll_scope($gwifip) == '') {
267
					$gwifip .= '%' . $gateway['interface'];
268
				}
269
			} else {
270
				$gwifip = find_interface_ipv6($gateway['interface'], true);
271
			}
272

    
273
			if (!is_ipaddrv6($gwifip)) {
274
				continue; //Skip this target
275
			}
276

    
277
			/*
278
			 * If the gateway is the same as the monitor we do not add a
279
			 * route as this will break the routing table.
280
			 * Add static routes for each gateway with their monitor IP
281
			 * not strictly necessary but is a added level of protection.
282
			 */
283
			if ($gateway['gateway'] != $gateways_arr[$gwname]['monitor']) {
284
				log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
285
				if (interface_isppp_type($gateway['friendlyiface'])) {
286
					route_add_or_change($gateway['monitor'],
287
					    '', $gateway['interface']);
288
					system_staticroutes_configure($gateway['friendlyiface']);
289
				} else {
290
					route_add_or_change($gateway['monitor'],
291
					    $gateway['gateway']);
292
				}
293

    
294
				pfSense_kill_states("::0.0.0.0/0", utf8_encode($gateway['monitor']), utf8_encode($gateway['interface']), "icmpv6");
295
			}
296
		} else {
297
			continue;
298
		}
299

    
300
		$monitor_ips[] = $gateway['monitor'];
301
		$gateways_arr[$gwname]['enable_dpinger'] = true;
302
		$gateways_arr[$gwname]['gwifip'] = $gwifip;
303
	}
304

    
305
	stop_dpinger();
306

    
307
	/* Start new processes */
308
	foreach ($gateways_arr as $gateway) {
309
		if (!isset($gateway['enable_dpinger'])) {
310
			continue;
311
		}
312

    
313
		if (start_dpinger($gateway) != 0) {
314
			log_error(sprintf(gettext("Error starting gateway monitor for %s"), $gateway['name']));
315
		}
316
	}
317

    
318
	return;
319
}
320

    
321
function get_dpinger_status($gwname, $gways = false, $action_disable = false) {
322
	global $g;
323

    
324
	$running_processes = running_dpinger_processes();
325

    
326
	if (!isset($running_processes[$gwname])) {
327
		log_error(sprintf(gettext(
328
		    'dpinger: No dpinger session running for gateway %s'),
329
		    $gwname));
330
		return false;
331
	}
332

    
333
	$proc = $running_processes[$gwname];
334
	unset($running_processes);
335

    
336
	$timeoutcounter = 0;
337
	while (true) {
338
		if (!file_exists($proc['socket'])) {
339
			log_error("dpinger: status socket {$proc['socket']} not found");
340
			return false;
341
		}
342
		$fp = @stream_socket_client("unix://{$proc['socket']}", $errno, $errstr, 10);
343
		if (!$fp) {
344
			log_error(sprintf(gettext('dpinger: cannot connect to status socket %1$s - %2$s (%3$s)'), $proc['socket'], $errstr, $errno));
345
			return false;
346
		}
347

    
348
		$status = '';
349
		while (!feof($fp)) {
350
			$status .= fgets($fp, 1024);
351
		}
352
		fclose($fp);
353

    
354
		$r = array();
355
		list(
356
			$r['gwname'],
357
			$r['latency_avg'],
358
			$r['latency_stddev'],
359
			$r['loss']
360
		) = explode(' ', preg_replace('/\n/', '', $status));
361

    
362
		// dpinger returns '<gwname> 0 0 0' when queried directly after it starts.
363
		// while a latency of 0 and a loss of 0 would be perfect, in a real world it doesnt happen.
364
		// or does it, anyone? if so we must 'detect' the initialization period differently..
365
		$ready = $r['latency_stddev'] != '0' || $r['loss'] != '0';
366

    
367
		if ($ready) {
368
			break;
369
		} else {
370
			$timeoutcounter++;
371
			if ($timeoutcounter > 300) {
372
				log_error(sprintf(gettext('dpinger: timeout while retrieving status for gateway %s'), $gwname));
373
				return false;
374
			}
375
			usleep(10000);
376
		}
377
	}
378

    
379
	$r['srcip'] = $proc['srcip'];
380
	$r['targetip'] = $proc['targetip'];
381

    
382
	if (is_array($gways)) {
383
		$gateways_arr = $gways;
384
	} else {
385
		$gateways_arr = return_gateways_array();
386
	}
387

    
388
	unset($gw);
389
	if (isset($gateways_arr[$gwname])) {
390
		$gw = $gateways_arr[$gwname];
391
	}
392

    
393
	$r['latency_avg'] = round($r['latency_avg']/1000, 3);
394
	$r['latency_stddev'] = round($r['latency_stddev']/1000, 3);
395

    
396
	$r['status'] = "online";
397
	$r['substatus'] = "none";
398
	if (isset($gw) && isset($gw['force_down'])) {
399
		$r['status'] = "down";
400
		$r['substatus'] = "force_down";
401
	} else if (isset($gw)) {
402
		$settings = return_dpinger_defaults();
403

    
404
		$keys = array(
405
		    'latencylow',
406
		    'latencyhigh',
407
		    'losslow',
408
		    'losshigh'
409
		);
410

    
411
		/* Replace default values by user-defined */
412
		foreach ($keys as $key) {
413
			if (isset($gw[$key]) && is_numeric($gw[$key])) {
414
				$settings[$key] = $gw[$key];
415
			}
416
		}
417

    
418
		if ($r['latency_avg'] > $settings['latencyhigh']) {
419
			if (!$action_disable) {
420
				$r['status'] = "down";
421
			}
422
			$r['substatus'] = "highdelay";
423
		} else if ($r['loss'] > $settings['losshigh']) {
424
			if (!$action_disable) {
425
				$r['status'] = "down";
426
			}
427
			$r['substatus'] = "highloss";
428
		} else if ($r['latency_avg'] > $settings['latencylow']) {
429
			$r['substatus'] = "delay";
430
		} else if ($r['loss'] > $settings['losslow']) {
431
			$r['substatus'] = "loss";
432
		}
433
	}
434

    
435
	return $r;
436
}
437

    
438
/* return the status of the dpinger targets as an array */
439
function return_gateways_status($byname = false, $gways = false) {
440
	global $config, $g;
441

    
442
	$dpinger_gws = running_dpinger_processes();
443
	$status = array();
444

    
445
	if (is_array($gways)) {
446
		$gateways_arr = $gways;
447
	} else {
448
		$gateways_arr = return_gateways_array();
449
	}
450

    
451
	foreach ($dpinger_gws as $gwname => $gwdata) {
452
		/*
453
		 * If action is disabled for this gateway, then we want a
454
		 * detailed status.  That reports "highdelay" or "highloss"
455
		 * rather than just "down".  Because reporting the gateway
456
		 * down would be misleading (gateway action is disabled)
457
		 */
458
		$action_disable = $gateways_arr[$gwname]['action_disable'];
459
		$dpinger_status = get_dpinger_status($gwname, $action_disable);
460
		if ($dpinger_status === false) {
461
			continue;
462
		}
463

    
464
		if ($byname == false) {
465
			$target = $dpinger_status['targetip'];
466
		} else {
467
			$target = $gwname;
468
		}
469

    
470
		$status[$target] = array();
471
		$status[$target]['monitorip'] = $dpinger_status['targetip'];
472
		$status[$target]['srcip'] = $dpinger_status['srcip'];
473
		$status[$target]['name'] = $gwname;
474
		$status[$target]['delay'] =
475
		    empty($dpinger_status['latency_avg'])
476
		    ? "0ms"
477
		    : $dpinger_status['latency_avg'] . "ms";
478
		$status[$target]['stddev'] =
479
		    empty($dpinger_status['latency_stddev'])
480
		    ? "0ms"
481
		    : $dpinger_status['latency_stddev'] . "ms";
482
		$status[$target]['loss'] = empty($dpinger_status['loss'])
483
		    ? "0.0%"
484
		    : round($dpinger_status['loss'], 1) . "%";
485
		$status[$target]['status'] = $dpinger_status['status'];
486
		$status[$target]['substatus'] = $dpinger_status['substatus'];
487
	}
488

    
489
	/* tack on any gateways that have monitoring disabled
490
	 * or are down, which could cause gateway groups to fail */
491
	$gateways_arr = return_gateways_array();
492
	foreach ($gateways_arr as $gwitem) {
493
		if (!isset($gwitem['monitor_disable'])) {
494
			continue;
495
		}
496
		if (!is_ipaddr($gwitem['monitor'])) {
497
			$realif = $gwitem['interface'];
498
			$tgtip = get_interface_gateway($realif);
499
			if (!is_ipaddr($tgtip)) {
500
				$tgtip = "none";
501
			}
502
			$srcip = find_interface_ip($realif);
503
		} else {
504
			$tgtip = $gwitem['monitor'];
505
			$srcip = find_interface_ip($realif);
506
		}
507
		if ($byname == true) {
508
			$target = $gwitem['name'];
509
		} else {
510
			$target = $tgtip;
511
		}
512

    
513
		/* failsafe for down interfaces */
514
		if ($target == "none") {
515
			$target = $gwitem['name'];
516
			$status[$target]['name'] = $gwitem['name'];
517
			$status[$target]['delay'] = "0.0ms";
518
			$status[$target]['loss'] = "100.0%";
519
			$status[$target]['status'] = "down";
520
			$status[$target]['substatus'] = "down";
521
		} else {
522
			$status[$target]['monitorip'] = $tgtip;
523
			$status[$target]['srcip'] = $srcip;
524
			$status[$target]['name'] = $gwitem['name'];
525
			$status[$target]['delay'] = "";
526
			$status[$target]['loss'] = "";
527
			$status[$target]['status'] = "online";
528
			$status[$target]['substatus'] = "none";
529
		}
530

    
531
		$status[$target]['monitor_disable'] = true;
532
	}
533
	return($status);
534
}
535

    
536
function return_gateways_status_text($byname = false, $brief = false) {
537
	$gwstat = return_gateways_status($byname);
538
	$output = "";
539
	$widths = array();
540
	$col_sep = 2;
541
	if ($brief) {
542
		$collist = array('status' => "Status");
543
	} else {
544
		$collist = array('monitorip' => "Monitor",
545
				'srcip' => "Source",
546
				'delay' => "Delay",
547
				'stddev' => "StdDev",
548
				'loss' => "Loss",
549
				'status' => "Status",
550
				'substatus' => "Substatus");
551
	}
552
	foreach ($gwstat as $gw) {
553
		foreach ($gw as $gwdidx => $gwdata) {
554
			if (strlen($gwdata) > $widths[$gwdidx]) {
555
				$widths[$gwdidx] = strlen($gwdata);
556
			}
557
		}
558
	}
559

    
560
	$output .= str_pad("Name", $widths['name'] + $col_sep, " ", STR_PAD_RIGHT);
561
	foreach ($collist as $hdrcol => $hdrdesc) {
562
		if (strlen($hdrdesc) > $widths[$hdrcol]) {
563
			$widths[$hdrcol] = strlen($hdrdesc);
564
		}
565
		$output .= str_pad($hdrdesc, $widths[$hdrcol] + $col_sep, " ", (substr($hdrcol, -2, 2) == "ip") ? STR_PAD_RIGHT : STR_PAD_LEFT);
566
	}
567
	$output .= "\n";
568

    
569
	foreach ($gwstat as $idx => $gw) {
570
		$output .= str_pad($gw['name'], $widths['name'] + $col_sep, " ", STR_PAD_RIGHT);
571
		foreach (array_keys($collist) as $col) {
572
			$output .= str_pad($gw[$col], $widths[$col] + $col_sep, " ", (substr($col, -2, 2) == "ip") ? STR_PAD_RIGHT : STR_PAD_LEFT);
573
		}
574
		$output .= "\n";
575
	}
576

    
577
	return $output;
578
}
579

    
580
function compare_gateway_order_configured($a, $b) {
581
	/* XXX WAN always has precedence */
582
	if ($a['friendlyiface'] == "wan") {
583
		return -1;
584
	} elseif ($b['friendlyiface'] == "wan") {
585
		return 1;
586
	}
587

    
588
	if ($a['attribute'] === $b['attribute']) {
589
		if ($a['attribute'] === 'system') {
590
			$res = (($a['name'] < $b['name'])) ? -1 : 1;
591
			return $res;
592
		}
593
		return 0;
594
	}
595
	if ($a['attribute'] === 'system' || $b['attribute'] === 'system') {
596
		$res = (($b['attribute'] === 'system')) ? -1 : 1;
597
		return $res;
598
	}
599
	$res = ($a['attribute'] < $b['attribute']) ? -1 : 1;
600
	return $res;
601
}
602

    
603
function order_gateways_as_configured($gateways_arr) {
604
	uasort($gateways_arr, 'compare_gateway_order_configured');
605
	return $gateways_arr;
606
}
607

    
608
/* Return all configured gateways on the system
609
   $disabled = true - include gateways that are disabled
610
   $localhost = true - include "Null" entries for localhost IP addresses
611
   $inactive = true - include gateways on inactive interfaces
612
   $integer_index = true - index the returned array by integers 0,1,2,... instead of by GW name
613
*/
614
function return_gateways_array($disabled = false, $localhost = false, $inactive = false, $integer_index = false) {
615
	global $config, $g;
616

    
617
	$gateways_arr = array();
618
	$gateways_arr_temp = array();
619
	$cgw4 = route_get_default('inet');
620
	$cgw6 = route_get_default('inet6');
621
	$found_defaultv4 = 0;
622
	$found_defaultv6 = 0;
623

    
624
	// Ensure the interface cache is up to date first
625
	$interfaces = get_interface_arr(true);
626

    
627
	$i = -1;
628
	/* Process/add all the configured gateways. */
629
	if (is_array($config['gateways']) && is_array($config['gateways']['gateway_item'])) {
630
		foreach ($config['gateways']['gateway_item'] as $gateway) {
631
			if (!is_array($gateway) || empty($gateway)) {
632
				continue;
633
			}
634

    
635
			/* Increment it here to do not skip items */
636
			$i++;
637
			if (isset($gateway['defaultgw'])) {
638
				unset($gateway['defaultgw']);
639
			}
640

    
641
			if (empty($config['interfaces'][$gateway['interface']])) {
642
				if ($inactive === false) {
643
					continue;
644
				} else {
645
					$gateway['inactive'] = true;
646
				}
647
			}
648
			$wancfg = $config['interfaces'][$gateway['interface']];
649

    
650
			/* skip disabled interfaces */
651
			if ($disabled === false && (!isset($wancfg['enable']))) {
652
				continue;
653
			}
654

    
655
			/* if the gateway is dynamic and we can find the IPv4, Great! */
656
			if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") {
657
				if ($gateway['ipprotocol'] == "inet") {
658
					/* we know which interfaces is dynamic, this should be made a function */
659
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
660
					/* no IP address found, set to dynamic */
661
					if (!is_ipaddrv4($gateway['gateway'])) {
662
						$gateway['gateway'] = "dynamic";
663
					}
664
					$gateway['dynamic'] = true;
665
				}
666

    
667
				/* if the gateway is dynamic and we can find the IPv6, Great! */
668
				else if ($gateway['ipprotocol'] == "inet6") {
669
					/* we know which interfaces is dynamic, this should be made a function, and for v6 too */
670
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
671
					/* no IPv6 address found, set to dynamic */
672
					if (!is_ipaddrv6($gateway['gateway'])) {
673
						$gateway['gateway'] = "dynamic";
674
					}
675
					$gateway['dynamic'] = true;
676
				}
677
			} else {
678
				/* getting this detection right is hard at this point because we still don't
679
				 * store the address family in the gateway item */
680
				if (is_ipaddrv4($gateway['gateway'])) {
681
					$gateway['ipprotocol'] = "inet";
682
				} else if (is_ipaddrv6($gateway['gateway'])) {
683
					$gateway['ipprotocol'] = "inet6";
684
				}
685
			}
686

    
687
			if (isset($gateway['monitor_disable'])) {
688
				$gateway['monitor_disable'] = true;
689
			} else if (empty($gateway['monitor'])) {
690
				$gateway['monitor'] = $gateway['gateway'];
691
			}
692

    
693
			if (isset($gateway['action_disable'])) {
694
				$gateway['action_disable'] = true;
695
			}
696

    
697
			$gateway['friendlyiface'] = $gateway['interface'];
698
			$gateway['friendlyifdescr'] = convert_friendly_interface_to_friendly_descr($gateway['interface']);
699

    
700
			/* special treatment for tunnel interfaces */
701
			if ($gateway['ipprotocol'] == "inet6") {
702
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet6", false, false);
703
			} else {
704
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet", false, false);
705
			}
706

    
707
			if ($gateway['ipprotocol'] == "inet" &&
708
					($gateway['gateway'] == $cgw4)) {
709
				$gateway['isdefaultgw'] = true;
710
				$found_defaultv4 = 1;
711
			} else if ($gateway['ipprotocol'] == "inet6" &&
712
					($gateway['gateway'] == $cgw6)) {
713
				$gateway['isdefaultgw'] = true;
714
				$found_defaultv6 = 1;
715
			}
716
			/* include the gateway index as the attribute */
717
			$gateway['attribute'] = $i;
718

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

    
723
			/* skip disabled gateways if the caller has not asked for them to be returned. */
724
			if (!($disabled === false && isset($gateway['disabled']))) {
725
				$gateways_arr[$gateway['name']] = $gateway;
726
			}
727
		}
728
	}
729
	unset($gateway);
730

    
731
	//Sort the array by GW name before moving on.
732
	ksort($gateways_arr, SORT_STRING | SORT_FLAG_CASE);
733

    
734
	/* Loop through all interfaces with a gateway and add it to a array */
735
	if ($disabled == false) {
736
		$iflist = get_configured_interface_with_descr();
737
	} else {
738
		$iflist = get_configured_interface_with_descr(true);
739
	}
740

    
741
	/* Process/add dynamic v4 gateways. */
742
	foreach ($iflist as $ifname => $friendly) {
743
		if (!interface_has_gateway($ifname)) {
744
			continue;
745
		}
746

    
747
		if (empty($config['interfaces'][$ifname])) {
748
			continue;
749
		}
750

    
751
		$ifcfg = &$config['interfaces'][$ifname];
752
		if (!isset($ifcfg['enable'])) {
753
			continue;
754
		}
755

    
756
		if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) {
757
			continue;
758
		}
759

    
760
		$ctype = "";
761
		switch ($ifcfg['ipaddr']) {
762
			case "dhcp":
763
			case "pppoe":
764
			case "l2tp":
765
			case "pptp":
766
			case "ppp":
767
				$ctype = strtoupper($ifcfg['ipaddr']);
768
				break;
769
			default:
770
				$tunnelif = substr($ifcfg['if'], 0, 3);
771
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
772
					switch (substr($ifcfg['if'], 4, 1)) {
773
						case "c":
774
							$ovpntype = "openvpn-client";
775
							break;
776
						case "s":
777
							$ovpntype = "openvpn-server";
778
							break;
779
						default:
780
							// unknown ovpn type
781
							continue 3;
782
					}
783
					$ovpnid = substr($ifcfg['if'], 5);
784
					if (is_array($config['openvpn'][$ovpntype])) {
785
						foreach ($config['openvpn'][$ovpntype] as & $ovpnconf) {
786
							if ($ovpnconf['vpnid'] == $ovpnid) {
787
								// skip IPv6-only interfaces
788
								if ($ovpnconf['create_gw'] == "v6only") {
789
									continue 3;
790
								}
791
								// skip tap interfaces
792
								if ($ovpnconf['dev_mode'] == "tap") {
793
									continue 3;
794
								}
795
							}
796
						}
797
					}
798
					$ctype = "VPNv4";
799
				} elseif (substr($ifcfg['if'], 0, 5) == "ipsec") {
800
					$ikeid = substr($ifcfg['if'], 5);
801
					if (is_array($config['ipsec']) && is_array($config['ipsec']['phase1']) && is_array($config['ipsec']['phase2'])) {
802
						foreach ($config['ipsec']['phase1'] as $ph1ent) {
803
							if ($ph1ent['disabled']) {
804
								continue;
805
							}
806
							$vtisubnet_spec = ipsec_vti($ph1ent, true);
807
							// Skip non-VTI tunnels
808
							if (!$vtisubnet_spec || !is_array($vtisubnet_spec)) {
809
								continue;
810
							}
811
							if (!isset($ph1ent['mobile']) && ($keyexchange == 'ikev1' || isset($ph1ent['splitconn']))) {
812
								foreach ($vtisubnet_spec as $idx => $vtisub) {
813
									if ($ifcfg['if'] == ("ipsec" . get_ipsecifnum($ph1ent['ikeid'], $idx))) {
814
										// If this specific VTI remote is v4, then we can make a v4 gw
815
										if (is_ipaddrv4($vtisub['right'])) {
816
											$ctype = "VTIv4";
817
										}
818
									}
819
								}
820
							} else {
821
								if ($ifcfg['if'] == ("ipsec" . get_ipsecifnum($ph1ent['ikeid'], 0))) {
822
									// If any of the VTI remotes are v4, then we can make a v4 gw
823
									foreach ($vtisubnet_spec as $vtisub) {
824
										if (is_ipaddrv4($vtisub['right'])) {
825
											$ctype = "VTIv4";
826
										}
827
									}
828
								}
829
							}
830
						}
831
						if (empty($ctype)) {
832
							continue 2;
833
						}
834
					}
835
				} elseif (substr($ifcfg['if'], 0, 2) == "wg") {
836
					if (!find_interface_ip($ifcfg['if'])) {
837
						continue 2;
838
					}
839
					$ctype = "WGv4";
840
				} elseif ($tunnelif == "gif" || $tunnelif == "gre") {
841
					$ctype = "TUNNELv4";
842
				}
843
				break;
844
		}
845
		$ctype = "_". strtoupper($ctype);
846

    
847
		$gateway = array();
848
		$gateway['dynamic'] = false;
849
		$gateway['ipprotocol'] = "inet";
850
		$gateway['gateway'] = get_interface_gateway($ifname, $gateway['dynamic']);
851
		$gateway['interface'] = get_real_interface($ifname);
852
		$gateway['friendlyiface'] = $ifname;
853
		$gateway['friendlyifdescr'] = convert_friendly_interface_to_friendly_descr($ifname);
854
		$gateway['name'] = "{$friendly}{$ctype}";
855
		$gateway['attribute'] = "system";
856

    
857
		if (($gateway['dynamic'] === "default") && ($found_defaultv4 == 0)) {
858
			$gateway['isdefaultgw'] = true;
859
			$gateway['dynamic'] = true;
860
			$found_defaultv4 = 1;
861
		}
862

    
863
		/* Loopback dummy for dynamic interfaces without a IP */
864
		if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) {
865
			$gateway['gateway'] = "dynamic";
866
		}
867

    
868
		/* automatically skip known static and dynamic gateways that were previously processed */
869
		foreach ($gateways_arr_temp as $gateway_item) {
870
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
871
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
872
				continue 2;
873
			}
874
		}
875

    
876
		if (is_ipaddrv4($gateway['gateway'])) {
877
			$gateway['monitor'] = $gateway['gateway'];
878
		}
879

    
880
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
881
		$gateways_arr[$gateway['name']] = $gateway;
882
	}
883
	unset($gateway);
884

    
885
	/* Process/add dynamic v6 gateways. */
886
	foreach ($iflist as $ifname => $friendly) {
887
		/* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */
888
		if (!isset($config['system']['ipv6allow'])) {
889
			break;
890
		}
891

    
892
		if (!interface_has_gatewayv6($ifname)) {
893
			continue;
894
		}
895

    
896
		if (empty($config['interfaces'][$ifname])) {
897
			continue;
898
		}
899

    
900
		$ifcfg = &$config['interfaces'][$ifname];
901
		if (!isset($ifcfg['enable'])) {
902
			continue;
903
		}
904

    
905
		if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) {
906
			continue;
907
		}
908

    
909
		$ctype = "";
910
		switch ($ifcfg['ipaddrv6']) {
911
			case "slaac":
912
			case "dhcp6":
913
			case "6to4":
914
			case "6rd":
915
				$ctype = strtoupper($ifcfg['ipaddrv6']);
916
				break;
917
			default:
918
				$tunnelif = substr($ifcfg['if'], 0, 3);
919
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
920
					switch (substr($ifcfg['if'], 4, 1)) {
921
						case "c":
922
							$ovpntype = "openvpn-client";
923
							break;
924
						case "s":
925
							$ovpntype = "openvpn-server";
926
							break;
927
						default:
928
							// unknown ovpn type
929
							continue 3;
930
					}
931
					$ovpnid = substr($ifcfg['if'], 5);
932
					if (is_array($config['openvpn'][$ovpntype])) {
933
						foreach ($config['openvpn'][$ovpntype] as & $ovpnconf) {
934
							if ($ovpnconf['vpnid'] == $ovpnid) {
935
								// skip IPv4-only interfaces
936
								if ($ovpnconf['create_gw'] == "v4only") {
937
									continue 3;
938
								}
939
								// skip tap interfaces
940
								if ($ovpnconf['dev_mode'] == "tap") {
941
									continue 3;
942
								}
943
							}
944
						}
945
					}
946
					$ctype = "VPNv6";
947
				} elseif (substr($ifcfg['if'], 0, 5) == "ipsec") {
948
					$ikeid = substr($ifcfg['if'], 5);
949
					if (is_array($config['ipsec']) && is_array($config['ipsec']['phase1']) && is_array($config['ipsec']['phase2'])) {
950
						foreach ($config['ipsec']['phase1'] as $ph1ent) {
951
							if ($ph1ent['disabled']) {
952
								continue;
953
							}
954
							$vtisubnet_spec = ipsec_vti($ph1ent, true);
955
							// Skip non-VTI tunnels
956
							if (!$vtisubnet_spec || !is_array($vtisubnet_spec)) {
957
								continue;
958
							}
959
							if (!isset($ph1ent['mobile']) && ($keyexchange == 'ikev1' || isset($ph1ent['splitconn']))) {
960
								foreach ($vtisubnet_spec as $idx => $vtisub) {
961
									if ($ifcfg['if'] == ("ipsec" . get_ipsecifnum($ph1ent['ikeid'], $idx))) {
962
										// If this specific VTI remote is v6, then we can make a v6 gw
963
										if (is_ipaddrv6($vtisub['right'])) {
964
											$ctype = "VTIv6";
965
										}
966
									}
967
								}
968
							} else {
969
								if ($ifcfg['if'] == ("ipsec" . get_ipsecifnum($ph1ent['ikeid'], 0))) {
970
									// If any of the VTI remotes are v6, then we can make a v6 gw
971
									foreach ($vtisubnet_spec as $vtisub) {
972
										if (is_ipaddrv6($vtisub['right'])) {
973
											$ctype = "VTIv6";
974
										}
975
									}
976
								}
977
							}
978
						}
979
						if (empty($ctype)) {
980
							continue 2;
981
						}
982
					}
983
				} elseif (substr($ifcfg['if'], 0, 2) == "wg") {
984
					if (!find_interface_ipv6($ifcfg['if'])) {
985
						continue 2;
986
					}
987
					$ctype = "WGv6";
988
				} else if ($tunnelif == "gif" || $tunnelif == "gre") {
989
					$ctype = "TUNNELv6";
990
				}
991
				break;
992
		}
993
		$ctype = "_". strtoupper($ctype);
994

    
995
		$gateway = array();
996
		$gateway['dynamic'] = false;
997
		$gateway['ipprotocol'] = "inet6";
998
		$gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']);
999
		$gateway['interface'] = get_real_interface($ifname, "inet6");
1000
		switch ($ifcfg['ipaddrv6']) {
1001
			case "6rd":
1002
			case "6to4":
1003
				$gateway['dynamic'] = "default";
1004
				break;
1005
		}
1006
		$gateway['friendlyiface'] = $ifname;
1007
		$gateway['friendlyifdescr'] = convert_friendly_interface_to_friendly_descr($ifname);
1008
		$gateway['name'] = "{$friendly}{$ctype}";
1009
		$gateway['attribute'] = "system";
1010

    
1011
		if (($gateway['dynamic'] === "default") && ($found_defaultv6 == 0)) {
1012
			$gateway['isdefaultgw'] = true;
1013
			$gateway['dynamic'] = true;
1014
			$found_defaultv6 = 1;
1015
		}
1016

    
1017
		/* Loopback dummy for dynamic interfaces without a IP */
1018
		if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) {
1019
			$gateway['gateway'] = "dynamic";
1020
		}
1021

    
1022
		/* automatically skip known static and dynamic gateways that were previously processed */
1023
		foreach ($gateways_arr_temp as $gateway_item) {
1024
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
1025
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
1026
				continue 2;
1027
			}
1028
		}
1029

    
1030
		if (is_ipaddrv6($gateway['gateway'])) {
1031
			$gateway['monitor'] = $gateway['gateway'];
1032
		}
1033

    
1034
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
1035
		$gateways_arr[$gateway['name']] = $gateway;
1036
	}
1037
	unset($gateway);
1038

    
1039
	/* FIXME: Should this be enabled.
1040
	 * Some interface like wan might be default but have no info recorded
1041
	 * the config. */
1042
	/* this is a fallback if all else fails and we want to get packets out @smos */
1043
	if ($found_defaultv4 == 0 || $found_defaultv6 == 0) {
1044
		foreach ($gateways_arr as &$gateway) {
1045
			if (($gateway['friendlyiface'] == "wan") && ($found_defaultv4 == 0) && (!isset($gateway['ipprotocol']) || ($gateway['ipprotocol'] == "inet"))) {
1046
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgw")) {
1047
					$gateway['isdefaultgw'] = true;
1048
					$found_defaultv4 = 1;
1049
				}
1050
			}
1051
			else if (($gateway['friendlyiface'] == "wan") && ($found_defaultv6 == 0) && ($gateway['ipprotocol'] == "inet6")) {
1052
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgwv6")) {
1053
					$gateway['isdefaultgw'] = true;
1054
					$found_defaultv6 = 1;
1055
				}
1056
			}
1057
		}
1058
	}
1059

    
1060
	if ($localhost === true) {
1061
		/* attach localhost for Null routes */
1062
		$gwlo4 = array();
1063
		$gwlo4['name'] = "Null4";
1064
		$gwlo4['interface'] = "lo0";
1065
		$gwlo4['ipprotocol'] = "inet";
1066
		$gwlo4['gateway'] = "127.0.0.1";
1067
		$gwlo4['attribute'] = "system";
1068
		$gwlo6 = array();
1069
		$gwlo6['name'] = "Null6";
1070
		$gwlo6['interface'] = "lo0";
1071
		$gwlo6['ipprotocol'] = "inet6";
1072
		$gwlo6['gateway'] = "::1";
1073
		$gwlo6['attribute'] = "system";
1074
		$gateways_arr['Null4'] = $gwlo4;
1075
		$gateways_arr['Null6'] = $gwlo6;
1076
	}
1077

    
1078
	if ($integer_index) {
1079
		$gateways_arr = array_values($gateways_arr);
1080
	}
1081

    
1082
	if ($found_defaultv4 != 1 && is_ipaddr($cgw4)) {
1083
		foreach($gateways_arr as &$gw) {
1084
			if ($gw['gateway'] == $cgw4) {
1085
				$gw['isdefaultgw'] = true;
1086
			}
1087
		}
1088
	}
1089
	if ($found_defaultv6 != 1 && is_ipaddr($cgw6)) {
1090
		foreach($gateways_arr as &$gw) {
1091
			if ($gw['gateway'] == $cgw6) {
1092
				$gw['isdefaultgw'] = true;
1093
			}
1094
		}
1095
	}
1096

    
1097
	$gways = order_gateways_as_configured($gateways_arr);
1098

    
1099
	// Add the tier names here so that system_gateways.php doesn't need to
1100
	foreach ($gways as $idx => $gway) {
1101
		$gways[$idx]['tiername'] = gateway_getgwtiername($gways, $idx);
1102
	}
1103

    
1104
	return $gways;
1105
}
1106

    
1107
function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
1108
	global $config, $g;
1109
	/*
1110
	 * NOTE: The code below is meant to replace the default gateway when it goes down.
1111
	 *	This facilitates services running on pfSense itself and are not handled by a PBR to continue working.
1112
	 */
1113
	$set_dfltgwname = '';
1114

    
1115
	if ($ipprotocol == 'inet') {
1116
		$gwdefault = $config['gateways']['defaultgw4'];
1117
	} else {
1118
		$gwdefault = $config['gateways']['defaultgw6'];
1119
	}
1120
	if ($gwdefault == "-") {
1121
		// 'none', dont set the default gateway, useful if routes are managed by frr/bgp/ospf or similar
1122
		return;
1123
	}
1124
	if (isset($gateways_arr[$gwdefault])) {
1125
		// the configured gateway is a regular one. (not a gwgroup) use it as is..
1126
		$set_dfltgwname = $gwdefault;
1127
	} elseif (empty($gwdefault)) {
1128
		// 'automatic' mode, pick the first one thats 'up' or 'unmonitored' which is always considered up
1129
		$gateways_arr = order_gateways_as_configured($gateways_arr);
1130
		$fallback = "";
1131
		foreach($gateways_arr as $gwname => $gwsttng) {
1132
			if ($gwsttng['ipprotocol'] != $ipprotocol) {
1133
				continue;
1134
			}
1135

    
1136
			if ((isset($gwsttng['monitor_disable']) || isset($gwsttng['action_disable']) || $gateways_status[$gwname]['status'] == "none")) {
1137
				$set_dfltgwname = $gwname;
1138
				break;
1139
			}
1140
			if (empty($fallback) && $gwsttng['interface'] != 'lo0') {
1141
				$fallback = $gwname;
1142
			}
1143
		}
1144
		if (empty($set_dfltgwname)) {
1145
			log_error(sprintf("Gateway, none 'available' for %s, use the first one configured. '%s'", $ipprotocol, $fallback));
1146
			$set_dfltgwname = $fallback;
1147
		}
1148
	} else {
1149
		// a gwgroup is selected
1150
		// find the best available gateway given options available..
1151
		$gwg_members = array();
1152
		$viplist = get_configured_vip_list();
1153
		if (is_array($config['gateways']['gateway_group'])) {
1154
			foreach ($config['gateways']['gateway_group'] as $group) {
1155
				if ($group['name'] == $gwdefault) {
1156
					// finds the gw members of the best available tier for this group.
1157
					$gwg_members = get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1158
				}
1159
			}
1160
		}
1161

    
1162
		if (count($gwg_members) > 0) {
1163
			$currentdefaultgwip = route_get_default($ipprotocol);
1164
			$found_current = false;
1165
			foreach($gwg_members as $gwgroupitem) {
1166
				if (!empty($currentdefaultgwip) && ($gwgroupitem['gwip'] == $currentdefaultgwip)) {
1167
					$set_dfltgwname = $gwgroupitem['gw'];
1168
					$found_current = true;
1169
					if (isset($config['system']['gw-debug'])) {
1170
						log_error("Keep current gateway, its already part of the group members.");
1171
					}
1172
					break;
1173
				}
1174
			}
1175
			if (!$found_current) {
1176
				$set_dfltgwname = $gwg_members[0]['gw'];
1177
				log_error(sprintf("Gateway, switch to: %s", $set_dfltgwname));
1178
			}
1179
		} else {
1180
			log_error("Gateway, NONE AVAILABLE");
1181
		}
1182
	}
1183
	if (!empty($set_dfltgwname) && isset($gateways_arr[$set_dfltgwname])) {
1184
		setdefaultgateway($gateways_arr[$set_dfltgwname]);
1185
	}
1186
}
1187

    
1188
function setdefaultgateway($gw) {
1189
	global $g, $config;
1190
	if (isset($config['system']['route-debug'])) {
1191
		file_put_contents("/dev/console", "\n[".getmypid()."] SET DEF GW: {$gw['name']}");
1192
	}
1193
	$ipprotocol = $gw['ipprotocol'];
1194
	if ($gw['gateway'] == "dynamic") {
1195
		if ($ipprotocol == 'inet') {
1196
			$gw['gateway'] = get_interface_gateway($gw['friendlyiface']);
1197
		} else {
1198
			$gw['gateway'] = get_interface_gateway_v6($$gw['friendlyiface']);
1199
		}
1200
	}
1201
	if ($ipprotocol == 'inet6' && !is_ipaddrv6($gw['gateway'])) {
1202
		return;
1203
	}
1204
	if ($ipprotocol == 'inet' && !is_ipaddrv4($gw['gateway'])) {
1205
		return;
1206
	}
1207
	if ($ipprotocol == 'inet6') {
1208
		if (is_linklocal($gw['gateway']) && get_ll_scope($gw['gateway']) == '') {
1209
			$gw['gateway'] .= "%" . $gw['interface'];
1210
		}
1211
	}
1212
	$currentdefaultgwip = route_get_default($ipprotocol);
1213
	if ($currentdefaultgwip != $gw['gateway']) {
1214
		log_error("Default gateway setting {$gw['descr']} as default.");
1215

    
1216
		if ($ipprotocol == 'inet') {
1217
			array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw", GLOB_BRACE));
1218
		} else {
1219
			array_map('unlink', glob("{$g['tmp_path']}/*_defaultgwv6", GLOB_BRACE));
1220
		}
1221
		$defaultif = get_real_interface($gw['interface']);
1222
		if ($defaultif) {
1223
			@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gw['gateway']);
1224
		}
1225

    
1226
		if (isset($gw["nonlocalgateway"])) {
1227
			if (is_ipaddr($gw['gateway']) && !empty($gw['interface'])) {
1228
				route_add_or_change($gw['gateway'], '',
1229
				    $gw['interface']);
1230
			}
1231
		}
1232
		if (isset($config['system']['route-debug'])) {
1233
			file_put_contents("/dev/console", "\n[".getmypid()."] SET DEF GW: {$gw['name']} ({$gw['gateway']})");
1234
		}
1235
		route_add_or_change("default", $gw['gateway'], '', '',
1236
		    $ipprotocol);
1237
		return true;
1238
	}
1239
}
1240

    
1241
function get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist){
1242
	$result = array();
1243
	/* create array with group gateways members separated by tier */
1244
	$tiers = array();
1245
	$backupplan = array();
1246
	$gwvip_arr = array();
1247
	foreach ($group['item'] as $item) {
1248
		list($gwname, $tier, $vipname) = explode("|", $item);
1249

    
1250
		if (is_ipaddr($viplist[$vipname])) {
1251
			if (!is_array($gwvip_arr[$group['name']])) {
1252
				$gwvip_arr[$group['name']] = array();
1253
			}
1254
			$gwvip_arr[$group['name']][$gwname] = $vipname;
1255
		}
1256

    
1257
		/* Do it here rather than reiterating again the group in case no member is up. */
1258
		if (!is_array($backupplan[$tier])) {
1259
			$backupplan[$tier] = array();
1260
		}
1261
		$backupplan[$tier][] = $gwname;
1262

    
1263
		/* check if the gateway is available before adding it to the array */
1264
		if (is_array($gateways_status[$gwname])) {
1265
			$status = $gateways_status[$gwname];
1266
			$gwdown = false;
1267
			if (stristr($status['status'], "down")) {
1268
				$gwdown = true;
1269
				switch ($status['substatus']) {
1270
					case "highloss":
1271
						$msg = sprintf(gettext('MONITOR: %1$s has packet loss, omitting from routing group %2$s'), $gwname, $group['name']);
1272
						break;
1273
					case "highdelay":
1274
						$msg = sprintf(gettext('MONITOR: %1$s has high latency, omitting from routing group %2$s'), $gwname, $group['name']);
1275
						break;
1276
					default:
1277
						$msg = sprintf(gettext('MONITOR: %1$s is down, omitting from routing group %2$s'), $gwname, $group['name']);
1278
				}
1279
			}
1280
			$statuschanged = false;
1281
			$pluginparams = array();
1282
			$pluginparams['type'] = 'gateway';
1283
			$pluginparams['name'] = $gwname;
1284
			if ($gwdown == true) {
1285
				if (!file_exists("/tmp/.down.{$gwname}")) {
1286
					@touch("/tmp/.down.{$gwname}");
1287
					$msg .= "\n".implode("|", $status);
1288
					$pluginparams['event'] = 'gateway.down';
1289
					$statuschanged = true;
1290
				}
1291
			} else {
1292
				/* Online add member */
1293
				if (!is_array($tiers[$tier])) {
1294
					$tiers[$tier] = array();
1295
				}
1296
				$tiers[$tier][] = $gwname;
1297
				if (unlink_if_exists("/tmp/.down.{$gwname}")) {
1298
					$msg = sprintf(gettext('MONITOR: %1$s is available now, adding to routing group %2$s'), $gwname, $group['name']);
1299
					$msg .= "\n".implode("|", $status);
1300
					$pluginparams['event'] = 'gateway.up';
1301
					$statuschanged = true;
1302
				}
1303
			}
1304
			if ($statuschanged) {
1305
				log_error($msg);
1306
				notify_all_remote($msg);
1307
				if (isset($gateways_arr[$gwname]['interface'])) {
1308
					$pluginparams['interface'] = $gateways_arr[$gwname]['interface'];
1309
				}
1310
				pkg_call_plugins('plugin_gateway', $pluginparams);
1311
			}
1312
		} else if (isset($gateways_arr[$gwname]['monitor_disable']) || isset($gateways_arr[$gwname]['action_disable'])) {
1313
			$tiers[$tier][] = $gwname;
1314
		}
1315
	}
1316
	$tiers_count = count($tiers);
1317
	if ($tiers_count == 0) {
1318
		/* Oh dear, we have no members! Engage Plan B */
1319
		if (isset($config['system']['gw-debug']) && (!platform_booting())) {
1320
			$msg = sprintf(gettext('Gateways status could not be determined, considering all as up/active. (Group: %s)'), $group['name']);
1321
			log_error($msg);
1322
		}
1323
		$tiers = $backupplan;
1324
	}
1325
	/* sort the tiers array by the tier key */
1326
	ksort($tiers);
1327

    
1328
	/* we do not really foreach the tiers as we stop after the first tier */
1329
	foreach ($tiers as $tieridx => $tier) {
1330
		/* process all gateways in this tier */
1331
		foreach ($tier as $member) {
1332
			/* determine interface gateway */
1333
			if (isset($gateways_arr[$member])) {
1334
				$gateway = $gateways_arr[$member];
1335
				$int = $gateway['interface'];
1336
				$gatewayip = "";
1337
				if (is_ipaddr($gateway['gateway'])) {
1338
					$gatewayip = $gateway['gateway'];
1339
				} else if (!empty($int)) {
1340
					$gatewayip = get_interface_gateway($gateway['friendlyiface']);
1341
				}
1342

    
1343
				if (!empty($int)) {
1344
					$result['ipprotocol'] = $gateway['ipprotocol'];
1345
					if (is_ipaddr($gatewayip)) {
1346
						$groupmember = array();
1347
						$groupmember['gw'] = $member;
1348
						$groupmember['int'] = $int;
1349
						$groupmember['gwip'] = $gatewayip;
1350
						$groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1;
1351
						if (is_array($gwvip_arr[$group['name']]) && !empty($gwvip_arr[$group['name']][$member])) {
1352
							$groupmember['vip'] = $gwvip_arr[$group['name']][$member];
1353
						}
1354
						$result[] = $groupmember;
1355
					}
1356
				}
1357
			}
1358
		}
1359
		/* we should have the 1st available tier now, exit stage left */
1360
		if (count($result) > 0) {
1361
			break;
1362
		} else {
1363
			log_error(sprintf(gettext('GATEWAYS: Group %1$s did not have any gateways up on tier %2$s!'), $group['name'], $tieridx));
1364
		}
1365
	}
1366
	// Add description field last to not influence the count() above
1367
	$result['descr'] = $group['descr'];
1368
	return $result;
1369
}
1370

    
1371
function get_gwgroup_members($groupname) {
1372
	global $config;
1373
	$gateways_status = return_gateways_status(true);
1374
	$gateways_arr = return_gateways_array();
1375
	$viplist = get_configured_vip_list();
1376
	foreach ($config['gateways']['gateway_group'] as $group) {
1377
		if ($group['name'] == $groupname) {
1378
			return get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1379
		}
1380
	}
1381
	return array();
1382
}
1383

    
1384
/*
1385
 * Return an array with all gateway groups with name as key
1386
 * All gateway groups will be processed before returning the array.
1387
 */
1388
function return_gateway_groups_array($fixup = false, $gways = false) {
1389
	global $config;
1390

    
1391
	/* fetch the current gateways status */
1392
	if (is_array($gways)) {
1393
		$gateways_status = $gways;
1394
	} else {
1395
		$gateways_status = return_gateways_status(true);
1396
	}
1397

    
1398
	$gateways_arr = return_gateways_array();
1399
	$gateway_groups_array = array();
1400
	if ($fixup == true) {
1401
		$gw4 = lookup_gateway_or_group_by_name($config['gateways']['defaultgw4'], $gways);
1402
		$gw6 = lookup_gateway_or_group_by_name($config['gateways']['defaultgw6'], $gways);
1403
		if ($gw4 && $gw4['type'] == 'gatewaygroup') {
1404
			fixup_default_gateway("inet", $gateways_status, $gateways_arr);
1405
		}
1406
		if ($gw6 && $gw6['type'] == 'gatewaygroup') {
1407
			fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
1408
		}
1409
	}
1410
	init_config_arr(array('gateways', 'gateway_group'));
1411
	if (!empty($config['gateways']['gateway_group'])) {
1412
		$viplist = get_configured_vip_list();
1413
		foreach ($config['gateways']['gateway_group'] as $group) {
1414
			$gateway_groups_array[$group['name']] = get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1415
		}
1416
	}
1417

    
1418
	return ($gateway_groups_array);
1419
}
1420

    
1421
/* Update DHCP WAN Interface ip address in gateway group item */
1422
function dhclient_update_gateway_groups_defaultroute($interface = "wan") {
1423
	global $config;
1424

    
1425
	if (is_array($config['gateways']['gateway_item'])) {
1426
		foreach ($config['gateways']['gateway_item'] as & $gw) {
1427
			if ($gw['interface'] != $interface) {
1428
				continue;
1429
			}
1430

    
1431
			$current_gw = get_interface_gateway($interface);
1432
			if ($gw['gateway'] <> $current_gw) {
1433
				$gw['gateway'] = $current_gw;
1434
				$changed = true;
1435
			}
1436
		}
1437
	}
1438

    
1439
	if ($changed && $current_gw) {
1440
		write_config(sprintf(gettext(
1441
		    'Updating gateway group gateway for %1$s - new gateway is %2$s'),
1442
		    $interface, $current_gw));
1443
	}
1444
}
1445

    
1446
function lookup_gateway_or_group_by_name($gwname, $gways = false) {
1447
	global $config;
1448

    
1449
	if (is_array($gways)) {
1450
		$gateways_arr = $gways;
1451
	} else {
1452
		$gateways_arr = return_gateways_array();
1453
	}
1454

    
1455
	foreach ($gateways_arr as $gw) {
1456
		if ($gw['name'] == $gwname) {
1457
			$gw['type'] = 'gateway';
1458
			return $gw;
1459
		}
1460
	}
1461

    
1462
	init_config_arr(array('gateways', 'gateway_group'));
1463
	foreach ($config['gateways']['gateway_group'] as $gwg) {
1464
		if ($gwg['name'] == $gwname) {
1465
			$gwg['type'] = 'gatewaygroup';
1466
			return $gwg;
1467
		}
1468
	}
1469

    
1470
	return false;
1471
}
1472

    
1473
function lookup_gateway_ip_by_name($name, $disabled = false) {
1474

    
1475
	$gateways_arr = return_gateways_array($disabled, true);
1476
	foreach ($gateways_arr as $gname => $gw) {
1477
		if ($gw['name'] === $name || $gname === $name) {
1478
			return $gw['gateway'];
1479
		}
1480
	}
1481

    
1482
	return false;
1483
}
1484

    
1485
function lookup_gateway_monitor_ip_by_name($name) {
1486

    
1487
	$gateways_arr = return_gateways_array(false, true);
1488
	if (!empty($gateways_arr[$name])) {
1489
		$gateway = $gateways_arr[$name];
1490
		if (!is_ipaddr($gateway['monitor'])) {
1491
			return $gateway['gateway'];
1492
		}
1493

    
1494
		return $gateway['monitor'];
1495
	}
1496

    
1497
	return (false);
1498
}
1499

    
1500
function lookup_gateway_interface_by_name($name) {
1501

    
1502
	$gateways_arr = return_gateways_array(false, true);
1503
	if (!empty($gateways_arr[$name])) {
1504
		$interfacegw = $gateways_arr[$name]['friendlyiface'];
1505
		return ($interfacegw);
1506
	}
1507

    
1508
	return (false);
1509
}
1510

    
1511
function get_root_interface($interface) {
1512
	if (substr($interface, 0, 4) == '_vip') {
1513
		$interface = get_configured_vip_interface($interface);
1514
		if (substr($interface, 0, 4) == '_vip') {
1515
			$interface = get_configured_vip_interface($interface);
1516
		}
1517
	}
1518
	return $interface;
1519
}
1520

    
1521
function get_interface_gateway($interface, &$dynamic = false) {
1522
	global $config, $g;
1523

    
1524
	$interface = get_root_interface($interface);
1525

    
1526
	$gw = NULL;
1527
	$gwcfg = $config['interfaces'][$interface];
1528
	if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) {
1529
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1530
			if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
1531
				$gw = $gateway['gateway'];
1532
				break;
1533
			}
1534
		}
1535
	}
1536

    
1537
	// for dynamic interfaces we handle them through the $interface_router file.
1538
	if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) {
1539
		$realif = get_real_interface($interface);
1540
		if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
1541
			$gw = trim(@file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
1542
			$dynamic = true;
1543
		}
1544
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) {
1545
			$dynamic = "default";
1546
		}
1547

    
1548
	}
1549

    
1550
	/* return gateway */
1551
	return ($gw);
1552
}
1553

    
1554
function get_interface_gateway_v6($interface, &$dynamic = false) {
1555
	global $config, $g;
1556

    
1557
	$interface = get_root_interface($interface);
1558

    
1559
	$gw = NULL;
1560
	$gwcfg = $config['interfaces'][$interface];
1561
	if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) {
1562
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1563
			if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
1564
				$gw = $gateway['gateway'];
1565
				break;
1566
			}
1567
		}
1568
	}
1569

    
1570
	// for dynamic interfaces we handle them through the $interface_router file.
1571
	if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) {
1572
		$realif = get_real_interface($interface);
1573
		if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
1574
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
1575
			$dynamic = true;
1576
		}
1577
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) {
1578
			$dynamic = "default";
1579
		}
1580
	}
1581
	/* return gateway */
1582
	return ($gw);
1583
}
1584

    
1585
/* Check a IP address against a gateway IP or name
1586
 * to verify it's address family */
1587
function validate_address_family($ipaddr, $gwname, $disabled = false) {
1588
	$v4ip = false;
1589
	$v6ip = false;
1590
	$v4gw = false;
1591
	$v6gw = false;
1592

    
1593
	if (is_ipaddrv4($ipaddr)) {
1594
		$v4ip = true;
1595
	}
1596
	if (is_ipaddrv6($ipaddr)) {
1597
		$v6ip = true;
1598
	}
1599
	if (is_ipaddrv4($gwname)) {
1600
		$v4gw = true;
1601
	}
1602
	if (is_ipaddrv6($gwname)) {
1603
		$v6gw = true;
1604
	}
1605

    
1606
	if ($v4ip && $v4gw) {
1607
		return true;
1608
	}
1609
	if ($v6ip && $v6gw) {
1610
		return true;
1611
	}
1612

    
1613
	/* still no match, carry on, lookup gateways */
1614
	if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname, $disabled))) {
1615
		$v4gw = true;
1616
	}
1617
	if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname, $disabled))) {
1618
		$v6gw = true;
1619
	}
1620

    
1621
	$gw_array = return_gateways_array();
1622
	if (is_array($gw_array[$gwname])) {
1623
		switch ($gw_array[$gwname]['ipprotocol']) {
1624
			case "inet":
1625
				$v4gw = true;
1626
				break;
1627
			case "inet6":
1628
				$v6gw = true;
1629
				break;
1630
		}
1631
	}
1632

    
1633
	if ($v4ip && $v4gw) {
1634
		return true;
1635
	}
1636
	if ($v6ip && $v6gw) {
1637
		return true;
1638
	}
1639

    
1640
	return false;
1641
}
1642

    
1643
/* check if a interface is part of a gateway group */
1644
function interface_gateway_group_member($interface, $gwgroup_name = "") {
1645
	global $config;
1646

    
1647
	if (is_array($config['gateways']['gateway_group'])) {
1648
		$groups = $config['gateways']['gateway_group'];
1649
	} else {
1650
		return false;
1651
	}
1652

    
1653
	$gateways_arr = return_gateways_array(false, true);
1654
	foreach ($groups as $group) {
1655
		if (is_array($group['item'])) {
1656
			foreach ($group['item'] as $item) {
1657
				$elements = explode("|", $item);
1658
				$gwname = $elements[0];
1659
				if ($interface == $gateways_arr[$gwname]['interface'] &&
1660
				    (empty($gwgroup_name) || $gwgroup_name == $group['name'])) {
1661
					unset($gateways_arr);
1662
					return true;
1663
				}
1664
			}
1665
		}
1666
	}
1667
	unset($gateways_arr);
1668

    
1669
	return false;
1670
}
1671

    
1672
function gateway_is_gwgroup_member($name, $detail=false) {
1673
	global $config;
1674

    
1675
	if (is_array($config['gateways']['gateway_group'])) {
1676
		$groups = $config['gateways']['gateway_group'];
1677
	} else {
1678
		return false;
1679
	}
1680

    
1681
	$members = array();
1682
	foreach ($groups as $group) {
1683
		if (is_array($group['item'])) {
1684
			foreach ($group['item'] as $item) {
1685
				list($gwname, $tier, $vipname) = explode("|", $item);
1686
				if ($name == $gwname) {
1687
					if ($detail) {
1688
						$newitem = array();
1689
						$newitem['name'] = $group['name'];
1690
						$newitem['tier'] = $tier;
1691
						$newitem['vipname'] = $vipname;
1692
						$members[] = $newitem;
1693
					} else {
1694
						$members[] = $group['name'];
1695
					}
1696
				}
1697
			}
1698
		}
1699
	}
1700

    
1701
	return $members;
1702
}
1703
/*
1704
  Check the proposed gateway settings to see if they are valid.
1705
  $gateway_settings - the proposed array of proposed gateway settings
1706
  $id - the index of the gateway proposed to be modified (otherwise "" if adding a new gateway)
1707
  $parent_ip - the IP (v4 or v6) address about to be set on the corresponding interface (if any)
1708
  $parent_sn - the subnet about to be set on the corresponding interface (if any)
1709
  (Note: the above 2 parameters allow gateway parameters to be validated concurrently with saving
1710
   an interface, before the new interface parameters are actually saved in the config.)
1711
  Return completed $input_errors array if there is any problem.
1712
  Otherwise return an empty $input_errors array
1713
*/
1714
function validate_gateway($gateway_settings, $id = "", $parent_ip = "", $parent_sn = "") {
1715
	global $config;
1716

    
1717
	$a_gateways = return_gateways_array(true, false, true, true);
1718
	$input_errors = array();
1719

    
1720
	/* input validation */
1721
	$reqdfields = explode(" ", "name interface");
1722
	$reqdfieldsn = array(gettext("Name"), gettext("Interface"));
1723

    
1724
	do_input_validation($gateway_settings, $reqdfields, $reqdfieldsn, $input_errors);
1725

    
1726
	if (!isset($gateway_settings['name'])) {
1727
		$input_errors[] = "A valid gateway name must be specified.";
1728
	}
1729
	if (!is_validaliasname($gateway_settings['name'])) {
1730
		$input_errors[] = invalidaliasnamemsg($gateway_settings['name'], gettext("gateway"));
1731
	} else if (isset($gateway_settings['disabled'])) {
1732
		// We have a valid gateway name that the user wants to mark as disabled.
1733
		// Check if the gateway name is used in any gateway group.
1734
		if (is_array($config['gateways']['gateway_group'])) {
1735
			foreach ($config['gateways']['gateway_group'] as $group) {
1736
				foreach ($group['item'] as $item) {
1737
					$items = explode("|", $item);
1738
					if ($items[0] == $gateway_settings['name']) {
1739
						$input_errors[] = sprintf(gettext('Gateway "%1$s" cannot be disabled because it is in use on Gateway Group "%2$s"'), $gateway_settings['name'], $group['name']);
1740
					}
1741
				}
1742
			}
1743
		}
1744

    
1745
		// Check if the gateway name is used in any enabled Static Route.
1746
		if (is_array($config['staticroutes']['route'])) {
1747
			foreach ($config['staticroutes']['route'] as $route) {
1748
				if ($route['gateway'] == $gateway_settings['name']) {
1749
					if (!isset($route['disabled'])) {
1750
						// There is a static route that uses this gateway and is enabled (not disabled).
1751
						$input_errors[] = sprintf(gettext('Gateway "%1$s" cannot be disabled because it is in use on Static Route "%2$s"'), $gateway_settings['name'], $route['network']);
1752
					}
1753
				}
1754
			}
1755
		}
1756
	}
1757
	/* skip system gateways which have been automatically added */
1758
	if (($gateway_settings['gateway'] && (!is_ipaddr($gateway_settings['gateway'])) && ($gateway_settings['attribute'] !== "system")) && ($gateway_settings['gateway'] != "dynamic")) {
1759
		$input_errors[] = gettext("A valid gateway IP address must be specified.");
1760
	}
1761

    
1762
	if ($gateway_settings['gateway'] && is_ipaddr($gateway_settings['gateway'])) {
1763
		if (is_ipaddrv4($gateway_settings['gateway'])) {
1764
			if ($parent_ip == '') {
1765
				$parent_ip = get_interface_ip($gateway_settings['interface']);
1766
				$parent_sn = get_interface_subnet($gateway_settings['interface']);
1767
			}
1768
			if (empty($parent_ip) || empty($parent_sn)) {
1769
				$input_errors[] = gettext("Cannot add IPv4 Gateway Address because no IPv4 address could be found on the interface.");
1770
			} elseif (!isset($gateway_settings["nonlocalgateway"])) {
1771
				$subnets = array(gen_subnet($parent_ip, $parent_sn) . "/" . $parent_sn);
1772
				$vips = link_interface_to_vips($gateway_settings['interface']);
1773
				if (is_array($vips)) {
1774
					foreach ($vips as $vip) {
1775
						if (!is_ipaddrv4($vip['subnet'])) {
1776
							continue;
1777
						}
1778
						$subnets[] = gen_subnet($vip['subnet'], $vip['subnet_bits']) . "/" . $vip['subnet_bits'];
1779
					}
1780
				}
1781

    
1782
				$found = false;
1783
				foreach ($subnets as $subnet) {
1784
					if (ip_in_subnet($gateway_settings['gateway'], $subnet)) {
1785
						$found = true;
1786
						break;
1787
					}
1788
				}
1789

    
1790
				if ($found === false) {
1791
					$input_errors[] = sprintf(gettext("The gateway address %s does not lie within one of the chosen interface's subnets."), $gateway_settings['gateway']);
1792
				}
1793
			}
1794
		} else if (is_ipaddrv6($gateway_settings['gateway'])) {
1795
			/* do not do a subnet match on a link local address, it's valid */
1796
			if (!is_linklocal($gateway_settings['gateway'])) {
1797
				if ($parent_ip == '') {
1798
					$parent_ip = get_interface_ipv6($gateway_settings['interface']);
1799
					$parent_sn = get_interface_subnetv6($gateway_settings['interface']);
1800
				}
1801
				if (empty($parent_ip) || empty($parent_sn)) {
1802
					$input_errors[] = gettext("Cannot add IPv6 Gateway Address because no IPv6 address could be found on the interface.");
1803
				} elseif (!isset($gateway_settings["nonlocalgateway"])) {
1804
					$subnets = array(gen_subnetv6($parent_ip, $parent_sn) . "/" . $parent_sn);
1805
					$vips = link_interface_to_vips($gateway_settings['interface']);
1806
					if (is_array($vips)) {
1807
						foreach ($vips as $vip) {
1808
							if (!is_ipaddrv6($vip['subnet'])) {
1809
								continue;
1810
							}
1811
							$subnets[] = gen_subnetv6($vip['subnet'], $vip['subnet_bits']) . "/" . $vip['subnet_bits'];
1812
						}
1813
					}
1814

    
1815
					$found = false;
1816
					foreach ($subnets as $subnet) {
1817
						if (ip_in_subnet($gateway_settings['gateway'], $subnet)) {
1818
							$found = true;
1819
							break;
1820
						}
1821
					}
1822

    
1823
					if ($found === false) {
1824
						$input_errors[] = sprintf(gettext("The gateway address %s does not lie within one of the chosen interface's subnets."), $gateway_settings['gateway']);
1825
					}
1826
				}
1827
			}
1828
		}
1829

    
1830
		if (!empty($config['interfaces'][$gateway_settings['interface']]['ipaddr'])) {
1831
			if (is_ipaddr($config['interfaces'][$gateway_settings['interface']]['ipaddr']) && (empty($gateway_settings['gateway']) || $gateway_settings['gateway'] == "dynamic")) {
1832
				$input_errors[] = gettext("Dynamic gateway values cannot be specified for interfaces with a static IPv4 configuration.");
1833
			}
1834
		}
1835
		if (!empty($config['interfaces'][$gateway_settings['interface']]['ipaddrv6'])) {
1836
			if (is_ipaddr($config['interfaces'][$gateway_settings['interface']]['ipaddrv6']) && (empty($gateway_settings['gateway']) || $gateway_settings['gateway'] == "dynamic")) {
1837
				$input_errors[] = gettext("Dynamic gateway values cannot be specified for interfaces with a static IPv6 configuration.");
1838
			}
1839
		}
1840
	}
1841
	if (($gateway_settings['monitor'] != "") && ($gateway_settings['monitor'] != "dynamic")) {
1842
		validateipaddr($gateway_settings['monitor'], IPV4V6, "Monitor IP", $input_errors, false);
1843
	}
1844
	if (isset($gateway_settings['data_payload']) && is_numeric($gateway_settings['data_payload']) && $gateway_settings['data_payload'] < 0) {
1845
		$input_errors[] = gettext("A valid data payload must be specified.");
1846
	}
1847
	/* only allow correct IPv4 and IPv6 gateway addresses */
1848
	if (($gateway_settings['gateway'] <> "") && is_ipaddr($gateway_settings['gateway']) && $gateway_settings['gateway'] != "dynamic") {
1849
		if (is_ipaddrv6($gateway_settings['gateway']) && ($gateway_settings['ipprotocol'] == "inet")) {
1850
			$input_errors[] = sprintf(gettext("The IPv6 gateway address '%s' can not be used as a IPv4 gateway."), $gateway_settings['gateway']);
1851
		}
1852
		if (is_ipaddrv4($gateway_settings['gateway']) && ($gateway_settings['ipprotocol'] == "inet6")) {
1853
			$input_errors[] = sprintf(gettext("The IPv4 gateway address '%s' can not be used as a IPv6 gateway."), $gateway_settings['gateway']);
1854
		}
1855
	}
1856
	/* only allow correct IPv4 and IPv6 monitor addresses */
1857
	if (($gateway_settings['monitor'] <> "") && is_ipaddr($gateway_settings['monitor']) && $gateway_settings['monitor'] != "dynamic") {
1858
		if (is_ipaddrv6($gateway_settings['monitor']) && ($gateway_settings['ipprotocol'] == "inet")) {
1859
			$input_errors[] = sprintf(gettext("The IPv6 monitor address '%s' can not be used on a IPv4 gateway."), $gateway_settings['monitor']);
1860
		}
1861
		if (is_ipaddrv4($gateway_settings['monitor']) && ($gateway_settings['ipprotocol'] == "inet6")) {
1862
			$input_errors[] = sprintf(gettext("The IPv4 monitor address '%s' can not be used on a IPv6 gateway."), $gateway_settings['monitor']);
1863
		}
1864
	}
1865

    
1866
	if (isset($gateway_settings['name'])) {
1867
		/* check for overlaps */
1868
		foreach ($a_gateways as $gateway) {
1869
			if (isset($id) && ($a_gateways[$id]) && ($a_gateways[$id] === $gateway)) {
1870
				if ($gateway['name'] != $gateway_settings['name']) {
1871
					$input_errors[] = gettext("Changing name on a gateway is not allowed.");
1872
				}
1873
				continue;
1874
			}
1875
			if ($gateway_settings['name'] <> "") {
1876
				if (($gateway['name'] <> "") && ($gateway_settings['name'] == $gateway['name']) && ($gateway['attribute'] !== "system")) {
1877
					$input_errors[] = sprintf(gettext('The gateway name "%s" already exists.'), $gateway_settings['name']);
1878
					break;
1879
				}
1880
			}
1881
			if (is_ipaddr($gateway_settings['gateway'])) {
1882
				if (($gateway['gateway'] <> "") && ($gateway_settings['gateway'] == $gateway['gateway']) && ($gateway['attribute'] !== "system")) {
1883
					$input_errors[] = sprintf(gettext('The gateway IP address "%s" already exists.'), $gateway_settings['gateway']);
1884
					break;
1885
				}
1886
			}
1887
			if (is_ipaddr($gateway_settings['monitor'])) {
1888
				if (($gateway['monitor'] <> "") && ($gateway_settings['monitor'] == $gateway['monitor']) && ($gateway['attribute'] !== "system")) {
1889
					$input_errors[] = sprintf(gettext('The monitor IP address "%s" is already in use. A different monitor IP must be chosen.'), $gateway_settings['monitor']);
1890
					break;
1891
				}
1892
			}
1893
		}
1894
	}
1895

    
1896
	/* input validation of dpinger advanced parameters */
1897

    
1898
	$dpinger_default = return_dpinger_defaults();
1899
	$latencylow = $dpinger_default['latencylow'];
1900
	if ($gateway_settings['latencylow']) {
1901
		if (!is_numeric($gateway_settings['latencylow'])) {
1902
			$input_errors[] = gettext("The low latency threshold needs to be a numeric value.");
1903
		} else if ($gateway_settings['latencylow'] < 1) {
1904
			$input_errors[] = gettext("The low latency threshold needs to be positive.");
1905
		} else {
1906
			$latencylow = $gateway_settings['latencylow'];
1907
		}
1908
	}
1909

    
1910
	$latencyhigh = $dpinger_default['latencyhigh'];
1911
	if ($gateway_settings['latencyhigh']) {
1912
		if (!is_numeric($gateway_settings['latencyhigh'])) {
1913
			$input_errors[] = gettext("The high latency threshold needs to be a numeric value.");
1914
		} else if ($gateway_settings['latencyhigh'] < 1) {
1915
			$input_errors[] = gettext("The high latency threshold needs to be positive.");
1916
		} else {
1917
			$latencyhigh = $gateway_settings['latencyhigh'];
1918
		}
1919
	}
1920

    
1921
	$losslow = $dpinger_default['losslow'];
1922
	if ($gateway_settings['losslow']) {
1923
		if (!is_numeric($gateway_settings['losslow'])) {
1924
			$input_errors[] = gettext("The low Packet Loss threshold needs to be a numeric value.");
1925
		} else if ($gateway_settings['losslow'] < 1) {
1926
			$input_errors[] = gettext("The low Packet Loss threshold needs to be positive.");
1927
		} else if ($gateway_settings['losslow'] >= 100) {
1928
			$input_errors[] = gettext("The low Packet Loss threshold needs to be less than 100.");
1929
		} else {
1930
			$losslow = $gateway_settings['losslow'];
1931
		}
1932
	}
1933

    
1934
	$losshigh = $dpinger_default['losshigh'];
1935
	if ($gateway_settings['losshigh']) {
1936
		if (!is_numeric($gateway_settings['losshigh'])) {
1937
			$input_errors[] = gettext("The high Packet Loss threshold needs to be a numeric value.");
1938
		} else if ($gateway_settings['losshigh'] < 1) {
1939
			$input_errors[] = gettext("The high Packet Loss threshold needs to be positive.");
1940
		} else if ($gateway_settings['losshigh'] > 100) {
1941
			$input_errors[] = gettext("The high Packet Loss threshold needs to be 100 or less.");
1942
		} else {
1943
			$losshigh = $gateway_settings['losshigh'];
1944
		}
1945
	}
1946

    
1947
	$time_period = $dpinger_default['time_period'];
1948
	if ($gateway_settings['time_period']) {
1949
		if (!is_numeric($gateway_settings['time_period'])) {
1950
			$input_errors[] = gettext("The time period over which results are averaged needs to be a numeric value.");
1951
		} else if ($gateway_settings['time_period'] < 1) {
1952
			$input_errors[] = gettext("The time period over which results are averaged needs to be positive.");
1953
		} else {
1954
			$time_period = $gateway_settings['time_period'];
1955
		}
1956
	}
1957

    
1958
	$interval = $dpinger_default['interval'];
1959
	if ($gateway_settings['interval']) {
1960
		if (!is_numeric($gateway_settings['interval'])) {
1961
			$input_errors[] = gettext("The probe interval needs to be a numeric value.");
1962
		} else if ($gateway_settings['interval'] < 1) {
1963
			$input_errors[] = gettext("The probe interval needs to be positive.");
1964
		} else {
1965
			$interval = $gateway_settings['interval'];
1966
		}
1967
	}
1968

    
1969
	$loss_interval = $dpinger_default['loss_interval'];
1970
	if ($gateway_settings['loss_interval']) {
1971
		if (!is_numeric($gateway_settings['loss_interval'])) {
1972
			$input_errors[] = gettext("The loss interval needs to be a numeric value.");
1973
		} else if ($gateway_settings['loss_interval'] < 1) {
1974
			$input_errors[] = gettext("The loss interval setting needs to be positive.");
1975
		} else {
1976
			$loss_interval = $gateway_settings['loss_interval'];
1977
		}
1978
	}
1979

    
1980
	$alert_interval = $dpinger_default['alert_interval'];
1981
	if ($gateway_settings['alert_interval']) {
1982
		if (!is_numeric($gateway_settings['alert_interval'])) {
1983
			$input_errors[] = gettext("The alert interval needs to be a numeric value.");
1984
		} else if ($gateway_settings['alert_interval'] < 1) {
1985
			$input_errors[] = gettext("The alert interval setting needs to be positive.");
1986
		} else {
1987
			$alert_interval = $gateway_settings['alert_interval'];
1988
		}
1989
	}
1990

    
1991
	if ($latencylow >= $latencyhigh) {
1992
		$input_errors[] = gettext(
1993
		    "The high latency threshold needs to be greater than the low latency threshold");
1994
	}
1995

    
1996
	if ($losslow >= $losshigh) {
1997
		$input_errors[] = gettext(
1998
		    "The high packet loss threshold needs to be higher than the low packet loss threshold");
1999
	}
2000

    
2001
	// If the loss interval is less than latencyhigh, then high latency could never be recorded
2002
	// because those high latency packets would be considered as lost. So do not allow that.
2003
	if ($latencyhigh > $loss_interval) {
2004
		$input_errors[] = gettext("The loss interval needs to be greater than or equal to the high latency threshold.");
2005
	}
2006

    
2007
	// Ensure that the time period is greater than 2 times the probe interval plus the loss interval.
2008
	if (($interval * 2 + $loss_interval) >= $time_period) {
2009
		$input_errors[] = gettext("The time period needs to be greater than twice the probe interval plus the loss interval.");
2010
	}
2011

    
2012
	// There is no point recalculating the average latency and loss more often than the probe interval.
2013
	// So the alert interval needs to be >= probe interval.
2014
	if ($interval > $alert_interval) {
2015
		$input_errors[] = gettext("The alert interval needs to be greater than or equal to the probe interval.");
2016
	}
2017

    
2018
	return $input_errors;
2019
}
2020

    
2021
// Save gateway settings.
2022
// $gateway_settings - the array of gateway setting parameters
2023
// $realid - the index of the gateway to be modified (otherwise "" if adding a new gateway)
2024

    
2025
// This function is responsible to:
2026
//   Setup the gateway parameter structure from the gateway settings input parameter
2027
//   Save the structure into the config
2028
//   Remove any run-time settings from gateway parameters that are changed (e.g. remove routes to addresses that are changing)
2029

    
2030
// A subsequent "apply" step will implement the added/changed gateway.
2031

    
2032
function save_gateway($gateway_settings, $realid = "") {
2033
	global $config;
2034

    
2035
	init_config_arr(array('gateways', 'gateway_item'));
2036
	$a_gateway_item = &$config['gateways']['gateway_item'];
2037
	$reloadif = "";
2038
	$gateway = array();
2039

    
2040
	if (empty($gateway_settings['interface'])) {
2041
		$gateway['interface'] = $gateway_settings['friendlyiface'];
2042
	} else {
2043
		$gateway['interface'] = $gateway_settings['interface'];
2044
	}
2045
	if (is_ipaddr($gateway_settings['gateway'])) {
2046
		$gateway['gateway'] = $gateway_settings['gateway'];
2047
	} else {
2048
		$gateway['gateway'] = "dynamic";
2049
	}
2050
	$gateway['name'] = $gateway_settings['name'];
2051
	$gateway['weight'] = $gateway_settings['weight'];
2052
	$gateway['ipprotocol'] = $gateway_settings['ipprotocol'];
2053
	if ($gateway_settings['interval']) {
2054
		$gateway['interval'] = $gateway_settings['interval'];
2055
	}
2056

    
2057
	if ($gateway_settings['time_period']) {
2058
		$gateway['time_period'] = $gateway_settings['time_period'];
2059
	}
2060
	if ($gateway_settings['alert_interval']) {
2061
		$gateway['alert_interval'] = $gateway_settings['alert_interval'];
2062
	}
2063

    
2064
	$gateway['descr'] = $gateway_settings['descr'];
2065
	if ($gateway_settings['monitor_disable'] == "yes") {
2066
		$gateway['monitor_disable'] = true;
2067
	}
2068
	if ($gateway_settings['action_disable'] == "yes") {
2069
		$gateway['action_disable'] = true;
2070
	}
2071
	if ($gateway_settings['nonlocalgateway'] == "yes") {
2072
		$gateway['nonlocalgateway'] = true;
2073
	}
2074
	if ($gateway_settings['force_down'] == "yes") {
2075
		$gateway['force_down'] = true;
2076
	}
2077
	if (is_ipaddr($gateway_settings['monitor'])) {
2078
		$gateway['monitor'] = $gateway_settings['monitor'];
2079
	}
2080
	if (isset($gateway_settings['data_payload']) && is_numeric($gateway_settings['data_payload']) && $gateway_settings['data_payload'] >= 0) {
2081
		$gateway['data_payload'] = $gateway_settings['data_payload'];
2082
	}
2083

    
2084
	/* NOTE: If gateway ip is changed need to cleanup the old static interface route */
2085
	if ($gateway_settings['monitor'] != "dynamic" &&
2086
	    !empty($a_gateway_item[$realid]) &&
2087
	    is_ipaddr($a_gateway_item[$realid]['gateway']) &&
2088
	    $gateway['gateway'] != $a_gateway_item[$realid]['gateway'] &&
2089
	    isset($a_gateway_item[$realid]["nonlocalgateway"])) {
2090
		route_del($a_gateway_item[$realid]['gateway']);
2091
	}
2092

    
2093
	/* NOTE: If monitor ip is changed need to cleanup the old static route */
2094
	if ($gateway_settings['monitor'] != "dynamic" &&
2095
	    !empty($a_gateway_item[$realid]) &&
2096
	    is_ipaddr($a_gateway_item[$realid]['monitor']) &&
2097
	    $gateway_settings['monitor'] != $a_gateway_item[$realid]['monitor'] &&
2098
	    $gateway['gateway'] != $a_gateway_item[$realid]['monitor']) {
2099
		route_del($a_gateway_item[$realid]['monitor']);
2100
	}
2101

    
2102
	if ($gateway_settings['defaultgw'] == "yes" || $gateway_settings['defaultgw'] == "on") {
2103
		// a new default gateway is being saved.
2104
		$i = 0;
2105
		/* remove the default gateway bits for all gateways with the same address family */
2106
		if (is_array($a_gateway_item)) {
2107
			foreach ($a_gateway_item as $gw) {
2108
				if ($gateway['ipprotocol'] == $gw['ipprotocol']) {
2109
					if ($gw['interface'] != $gateway_settings['interface'] &&
2110
						($gw['name'] == $config['gateways']['defaultgw4'] || $gw['name'] == $config['gateways']['defaultgw6'])) {
2111
						// remember the old default gateway interface to call with a "interface reconfigure" event.
2112
						$reloadif = $gw['interface'];
2113
					}
2114
				}
2115
				$i++;
2116
			}
2117
		}
2118
		if ($gateway['ipprotocol'] == "inet") {
2119
			$config['gateways']['defaultgw4'] = $gateway['name'];
2120
		} elseif ($gateway['ipprotocol'] == "inet6") {
2121
			$config['gateways']['defaultgw6'] = $gateway['name'];
2122
		}
2123
	}
2124

    
2125
	if ($gateway_settings['latencylow']) {
2126
		$gateway['latencylow'] = $gateway_settings['latencylow'];
2127
	}
2128
	if ($gateway_settings['latencyhigh']) {
2129
		$gateway['latencyhigh'] = $gateway_settings['latencyhigh'];
2130
	}
2131
	if ($gateway_settings['losslow']) {
2132
		$gateway['losslow'] = $gateway_settings['losslow'];
2133
	}
2134
	if ($gateway_settings['losshigh']) {
2135
		$gateway['losshigh'] = $gateway_settings['losshigh'];
2136
	}
2137
	if ($gateway_settings['loss_interval']) {
2138
		$gateway['loss_interval'] = $gateway_settings['loss_interval'];
2139
	}
2140
	/* when saving the manual gateway we use the attribute which has the corresponding id */
2141
	if (isset($realid) && $a_gateway_item[$realid]) {
2142
		$preserve_disabled = isset($a_gateway_item[$realid]['disabled']);
2143
		$a_gateway_item[$realid] = $gateway;
2144
		if ($preserve_disabled) {
2145
			$a_gateway_item[$realid]['disabled'] = true;
2146
		}
2147
	} else {
2148
		$a_gateway_item[] = $gateway;
2149
	}
2150
	gateway_set_enabled($gateway_settings['name'], !isset($gateway_settings['disabled']));
2151

    
2152
	mark_subsystem_dirty('staticroutes');
2153

    
2154
	write_config("Gateway settings changed");
2155

    
2156
	if (!empty($reloadif)) {
2157
		send_event("interface reconfigure {$reloadif}");
2158
	}
2159
}
2160

    
2161
function gateway_set_enabled($name, $enabled) {
2162
	global $config;
2163
	if (is_array($config['gateways']['gateway_item'])) {
2164
		foreach($config['gateways']['gateway_item'] as &$item) {
2165
			if ($item['name'] == $name) {
2166
				$gateway = &$item;
2167
			}
2168
		}
2169
	}
2170
	if (!isset($gateway)) {
2171
		return;
2172
	}
2173
	if ($enabled) {
2174
		unset($gateway['disabled']);
2175
	} else {
2176
		/* Check if the gateway was enabled but changed to disabled. */
2177
		if (!isset($gateway['disabled'])) {
2178
			/*  If the disabled gateway was the default route, remove the default route */
2179
			if (is_ipaddr($gateway['gateway'])) {
2180
				$inet = (!is_ipaddrv4($gateway['gateway']) ? 'inet6' : 'inet');
2181
				if ($inet == 'inet') {
2182
					$cgw = route_get_default('inet');
2183
				} else {
2184
					$cgw = route_get_default('inet6');
2185
				}
2186
				if ($gateway['gateway'] == $cgw) {
2187
					route_del("default", $inet);
2188
				}
2189
			}
2190
			$gateway['disabled'] = true;
2191
		}
2192
	}
2193
}
2194

    
2195
function gateway_or_gwgroup_exists($name) {
2196
	global $config;
2197
	if (is_array($config['gateways']['gateway_item'])) {
2198
		foreach($config['gateways']['gateway_item'] as $item) {
2199
			if ($item['name'] == $name) {
2200
				return true;
2201
			}
2202
		}
2203
	}
2204
	if (is_array($config['gateways']['gateway_group'])) {
2205
		foreach($config['gateways']['gateway_group'] as $item) {
2206
			if ($item['name'] == $name) {
2207
				return true;
2208
			}
2209
		}
2210
	}
2211
	return false;
2212
}
2213

    
2214
// These two replacement functions avoid the need to call return_gateways_array() multiple times and
2215
// allow system_gateways.php to get everything it needs in a single function call
2216
function gateway_getgwtiername($gways, $idx) {
2217
	global $config;
2218

    
2219
	$result = "";
2220
	$gwname = $gways[$idx]['name'];
2221

    
2222
	$gw = get_gateway_or_group_by_name($gwname, $gways);
2223
	init_config_arr(array('gateways'));
2224
	if ($config['gateways']['defaultgw4'] == $gwname || $config['gateways']['defaultgw6'] == $gwname) {
2225
		$result = "Default";
2226
	} else {
2227
		if ($gw['ipprotocol'] == 'inet') {
2228
			$defgw = get_gateway_or_group_by_name($config['gateways']['defaultgw4'], $gways);
2229
		} else {
2230
			$defgw = get_gateway_or_group_by_name($config['gateways']['defaultgw6'], $gways);
2231
		}
2232

    
2233
		if ($defgw['type'] == "gatewaygroup") {
2234
			$detail = gateway_is_gwgroup_member($gwname, true);
2235
			foreach($detail as $gwitem) {
2236
				if ($gwitem['name'] == $defgw['name']) {
2237
					if (isset($gwitem['tier'])) {
2238
						$result = "Tier " . $gwitem['tier'];
2239
						break;
2240
					}
2241
				}
2242
			}
2243
		}
2244
    }
2245

    
2246
	if (!empty($result)) {
2247
		if ($gw['ipprotocol'] == "inet") {
2248
			$result .= " (IPv4)";
2249
		} elseif ($gw['ipprotocol'] == "inet6") {
2250
			$result .= " (IPv6)";
2251
		}
2252
	}
2253

    
2254
	return $result;
2255
}
2256

    
2257
function get_gateway_or_group_by_name($gwname, $gateways_arr) {
2258
	global $config;
2259

    
2260
	foreach ($gateways_arr as $gw) {
2261
		if ($gw['name'] == $gwname) {
2262
			$gw['type'] = 'gateway';
2263
			return $gw;
2264
		}
2265
	}
2266

    
2267
	init_config_arr(array('gateways', 'gateway_group'));
2268
	foreach ($config['gateways']['gateway_group'] as $gwg) {
2269
		if ($gwg['name'] == $gwname) {
2270
			$gwg['type'] = 'gatewaygroup';
2271
			return $gwg;
2272
		}
2273
	}
2274

    
2275
	return false;
2276
}
2277

    
2278
// Compose a list of available gateways but without the need to call return_gateways_array() multiple times
2279
// Previously that function could be called eight times per gateway!
2280
function available_default_gateways() {
2281
	global $config;
2282

    
2283
	$gways = return_gateways_array(true, false, true, true);
2284

    
2285
	$items4 = array();
2286
	$items6 = array();
2287
	$items4[''] = "Automatic";
2288
	$items6[''] = "Automatic";
2289
	foreach($gways as $gw) {
2290
		$gwn = $gw['name'];
2291
		if ($gw['ipprotocol'] == "inet6") {
2292
			$items6[$gwn] = $gwn;
2293
		} else {
2294
			$items4[$gwn] = $gwn;
2295
		}
2296
	}
2297

    
2298
	$groups = return_gateway_groups_array(false, $gways);
2299
	foreach ($groups as $key => $group) {
2300
		$gwn = $group['descr'];
2301
		if ($group['ipprotocol'] == "inet6") {
2302
			$items6[$key] = "$key ($gwn)";
2303
		} else {
2304
			$items4[$key] = "$key ($gwn)";
2305
		}
2306
	}
2307
	$items4['-'] = "None";
2308
	$items6['-'] = "None";
2309

    
2310
	$defaults = array();
2311
	$defaults['v4'] = $items4;
2312
	$defaults['v6'] = $items6;
2313
	$defaults['defaultgw4'] = $config['gateways']['defaultgw4'];
2314
	$defaults['defaultgw6'] = $config['gateways']['defaultgw6'];
2315

    
2316
	return $defaults;
2317
}
2318

    
2319

    
2320
?>
(21-21/61)