Project

General

Profile

Download (76.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * gwlb.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2008 Bill Marquette, Seth Mos
7
 * Copyright (c) 2008-2013 BSD Perimeter
8
 * Copyright (c) 2013-2016 Electric Sheep Fencing
9
 * Copyright (c) 2014-2022 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
require_once("util.inc");
30

    
31
global $gateway_state_kill_modes;
32
$gateway_state_kill_modes = array(
33
	'' => gettext("Use global behavior (default)"),
34
	'none' => gettext("Do not kill states on gateway failure"),
35
	'down' => gettext("Kill states using this gateway when it is down"),
36
);
37

    
38
/* Returns an array of default values used for dpinger */
39
function return_dpinger_defaults() {
40
	return array(
41
		"latencylow" => "200",
42
		"latencyhigh" => "500",
43
		"losslow" => "10",
44
		"losshigh" => "20",
45
		"interval" => "500",
46
		"loss_interval" => "2000",
47
		"time_period" => "60000",
48
		"alert_interval" => "1000",
49
		"data_payload" => "1");
50
}
51

    
52
function running_dpinger_processes() {
53
	global $g;
54

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

    
57
	$result = array();
58
	if ($pidfiles === FALSE) {
59
		return $result;
60
	}
61

    
62
	foreach ($pidfiles as $pidfile) {
63
		if (preg_match('/^dpinger_(.+)~([^~]+)~([^~]+)\.pid$/',
64
		    basename($pidfile), $matches)) {
65
			$socket_file = preg_replace('/\.pid$/', '.sock',
66
			    $pidfile);
67
			$result[$matches[1]] = array(
68
			    'srcip'    => $matches[2],
69
			    'targetip' => $matches[3],
70
			    'pidfile'  => $pidfile,
71
			    'socket'   => $socket_file
72
			);
73
			unset($gwinfo);
74
		}
75
	}
76

    
77
	return $result;
78
}
79

    
80
/*
81
 * Stop one or more dpinger process
82
 * default parameter $gwname is '*' that will kill all running sessions
83
 * If a gateway name is passed, only this one will be killed
84
 */
85
function stop_dpinger($gwname = '') {
86
	global $g;
87

    
88
	$running_processes = running_dpinger_processes();
89

    
90
	foreach ($running_processes as $running_gwname => $process) {
91
		if ($gwname != '' && $running_gwname != $gwname) {
92
			continue;
93
		}
94

    
95
		if (isvalidpid($process['pidfile'])) {
96
			killbypid($process['pidfile'], 3);
97
		} else {
98
			@unlink($process['pidfile']);
99
		}
100
	}
101
}
102

    
103
function start_dpinger($gateway) {
104
	global $g;
105

    
106
	if (!isset($gateway['gwifip'])) {
107
		return (false);
108
	}
109

    
110
	$dpinger_defaults = return_dpinger_defaults();
111

    
112
	$prefix = "{$g['varrun_path']}/dpinger_{$gateway['name']}~" .
113
	    "{$gateway['gwifip']}~{$gateway['monitor']}";
114
	# dpinger socket path should not be longer then uaddr.sun_path
115
	if (strlen($prefix) > 95) {
116
		$prefix = "{$g['varrun_path']}/dpinger_{$gateway['name']}~" .
117
		    substr(md5($gateway['gwifip']),0,8) . "~" .
118
		    $gateway['monitor'];
119
	}
120
	$pidfile = $prefix . ".pid";
121
	$socket = $prefix . ".sock";
122
	$alarm_cmd = "{$g['etc_path']}/rc.gateway_alarm";
123

    
124
	$params  = "-S ";			/* Log warnings via syslog */
125
	$params .= "-r 0 ";			/* Disable unused reporting thread */
126
	$params .= "-i {$gateway['name']} ";	/* Identifier */
127
	$params .= "-B {$gateway['gwifip']} ";	/* Bind src address */
128
	$params .= "-p {$pidfile} ";		/* PID filename */
129
	$params .= "-u {$socket} ";		/* Status Socket */
130
	if (!$gateway['action_disable']) {
131
		$params .= "-C \"{$alarm_cmd}\" ";	/* Command to run on alarm */
132
	}
133

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

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

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

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

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

    
164
	$params .= "-D " .
165
	    (isset($gateway['latencyhigh']) && is_numeric($gateway['latencyhigh'])
166
	    ?  $gateway['latencyhigh']
167
	    : $dpinger_defaults['latencyhigh']
168
	    ) . " ";
169

    
170
	$params .= "-L " .
171
	    (isset($gateway['losshigh']) && is_numeric($gateway['losshigh'])
172
	    ?  $gateway['losshigh']
173
	    : $dpinger_defaults['losshigh']
174
	    ) . " ";
175

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

    
179
	/* Do not try to bind IPv6 where interface is in tentative state */
180
	if (is_ipaddrv6($gateway['gwifip'])) {
181
		$err = interface_wait_tentative(get_real_interface(
182
		    $gateway['interface']));
183
		if ($err == false) {
184
			log_error(gettext("Timeout waiting for IPv6 address in tentative state.  dpinger will not run."));
185
			return (false);
186
		}
187
	}
188

    
189
	/* Redirect stdout to /dev/null to avoid exec() to wait for dpinger */
190
	return mwexec("/usr/local/bin/dpinger {$params} {$gateway['monitor']} >/dev/null");
191
}
192

    
193
/*
194
 * Starts dpinger processes and adds appropriate static routes for monitor IPs
195
 */
196
function setup_gateways_monitor() {
197
	global $config, $g;
198

    
199
	$gateways_arr = return_gateways_array();
200
	if (!is_array($gateways_arr)) {
201
		log_error(gettext("No gateways to monitor. dpinger will not run."));
202
		stop_dpinger();
203
		return;
204
	}
205
	if (platform_booting()) {
206
		echo "Setting up gateway monitors...";
207
	}
208
	$monitor_ips = array();
209
	foreach ($gateways_arr as $gwname => $gateway) {
210
		/* Do not monitor if such was requested */
211
		if (isset($gateway['monitor_disable'])) {
212
			continue;
213
		}
214
		if (empty($gateway['monitor']) || !is_ipaddr($gateway['monitor'])) {
215
			if (is_ipaddr($gateway['gateway'])) {
216
				$gateways_arr[$gwname]['monitor'] = $gateway['gateway'];
217
			} else { /* No chance to get an ip to monitor skip target. */
218
				continue;
219
			}
220
		}
221

    
222
		/* if the monitor address is already used before, skip */
223
		if (in_array($gateway['monitor'], $monitor_ips)) {
224
			continue;
225
		}
226

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

    
240
			if ($gwifip == "0.0.0.0") {
241
				continue; //Skip this target - the gateway is still waiting for DHCP
242
			}
243

    
244
			/*
245
			 * If the gateway is the same as the monitor we do not add a
246
			 * route as this will break the routing table.
247
			 * Add static routes for each gateway with their monitor IP
248
			 * not strictly necessary but is a added level of protection.
249
			 */
250
			if (!isset($config['system']['dpinger_dont_add_static_routes']) &&
251
					!isset($gateway['dpinger_dont_add_static_route'])) {
252
				if (is_ipaddrv4($gateway['gateway']) && $gateway['monitor'] != $gateway['gateway']) {
253
					log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
254
					if (interface_isppp_type($gateway['friendlyiface'])) {
255
						route_add_or_change($gateway['monitor'],
256
						    '', $gateway['interface']);
257
						system_staticroutes_configure($gateway['friendlyiface']);
258
					} else {
259
						route_add_or_change($gateway['monitor'],
260
						    $gateway['gateway']);
261
					}
262

    
263
					pfSense_kill_states("0.0.0.0/0", utf8_encode($gateway['monitor']), utf8_encode($gateway['interface']), "icmp");
264
				}
265
			}
266
		} else if ($gateway['ipprotocol'] == "inet6") { // This is an IPv6 gateway...
267
			if (is_linklocal($gateway['gateway']) &&
268
			    get_ll_scope($gateway['gateway']) == '') {
269
				$gateway['gateway'] .= '%' . $gateway['interface'];
270
			}
271

    
272
			if (is_linklocal($gateway['monitor'])) {
273
				if (get_ll_scope($gateway['monitor']) == '') {
274
					$gateways_arr[$gwname]['monitor'] .= '%' . $gateway['interface'];
275
				}
276

    
277
				$gwifip = find_interface_ipv6_ll($gateway['interface'], true);
278

    
279
				if (get_ll_scope($gwifip) == '') {
280
					$gwifip .= '%' . $gateway['interface'];
281
				}
282
			} else {
283
				$gwifip = find_interface_ipv6($gateway['interface'], true);
284
			}
285

    
286
			if (!is_ipaddrv6($gwifip)) {
287
				continue; //Skip this target
288
			}
289

    
290
			/*
291
			 * If the gateway is the same as the monitor we do not add a
292
			 * route as this will break the routing table.
293
			 * Add static routes for each gateway with their monitor IP
294
			 * not strictly necessary but is a added level of protection.
295
			 */
296

    
297
			if (!isset($config['system']['dpinger_dont_add_static_routes']) &&
298
					!isset($gateway['dpinger_dont_add_static_route'])) {
299
				if ($gateway['gateway'] != $gateways_arr[$gwname]['monitor']) {
300
					log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
301
					if (interface_isppp_type($gateway['friendlyiface'])) {
302
						route_add_or_change($gateway['monitor'],
303
						    '', $gateway['interface']);
304
						system_staticroutes_configure($gateway['friendlyiface']);
305
					} else {
306
						route_add_or_change($gateway['monitor'],
307
						    $gateway['gateway']);
308
					}
309

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

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

    
322
	stop_dpinger();
323

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

    
330
		if (start_dpinger($gateway) != 0) {
331
			log_error(sprintf(gettext("Error starting gateway monitor for %s"), $gateway['name']));
332
		}
333
	}
334
	if (platform_booting()) {
335
		echo "done.\n";
336
	}
337

    
338
	return;
339
}
340

    
341
function get_dpinger_status($gwname, $gways = false, $action_disable = false) {
342
	global $g;
343

    
344
	$running_processes = running_dpinger_processes();
345

    
346
	if (!isset($running_processes[$gwname])) {
347
		log_error(sprintf(gettext(
348
		    'dpinger: No dpinger session running for gateway %s'),
349
		    $gwname));
350
		return false;
351
	}
352

    
353
	$proc = $running_processes[$gwname];
354
	unset($running_processes);
355

    
356
	$timeoutcounter = 0;
357
	while (true) {
358
		if (!file_exists($proc['socket'])) {
359
			log_error("dpinger: status socket {$proc['socket']} not found");
360
			return false;
361
		}
362
		$fp = @stream_socket_client("unix://{$proc['socket']}", $errno, $errstr, 10);
363
		if (!$fp) {
364
			log_error(sprintf(gettext('dpinger: cannot connect to status socket %1$s - %2$s (%3$s)'), $proc['socket'], $errstr, $errno));
365
			return false;
366
		}
367

    
368
		$status = '';
369
		while (!feof($fp)) {
370
			$status .= fgets($fp, 1024);
371
		}
372
		fclose($fp);
373

    
374
		$r = array();
375
		list(
376
			$r['gwname'],
377
			$r['latency_avg'],
378
			$r['latency_stddev'],
379
			$r['loss']
380
		) = explode(' ', preg_replace('/\n/', '', $status));
381

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

    
387
		if ($ready) {
388
			break;
389
		} else {
390
			$timeoutcounter++;
391
			if ($timeoutcounter > 300) {
392
				log_error(sprintf(gettext('dpinger: timeout while retrieving status for gateway %s'), $gwname));
393
				return false;
394
			}
395
			usleep(10000);
396
		}
397
	}
398

    
399
	$r['srcip'] = $proc['srcip'];
400
	$r['targetip'] = $proc['targetip'];
401

    
402
	if (is_array($gways)) {
403
		$gateways_arr = $gways;
404
	} else {
405
		$gateways_arr = return_gateways_array();
406
	}
407

    
408
	unset($gw);
409
	if (isset($gateways_arr[$gwname])) {
410
		$gw = $gateways_arr[$gwname];
411
	}
412

    
413
	$r['latency_avg'] = round($r['latency_avg']/1000, 3);
414
	$r['latency_stddev'] = round($r['latency_stddev']/1000, 3);
415

    
416
	$r['status'] = "online";
417
	$r['substatus'] = "none";
418
	if (isset($gw) && isset($gw['force_down'])) {
419
		$r['status'] = "down";
420
		$r['substatus'] = "force_down";
421
	} else if (isset($gw)) {
422
		$settings = return_dpinger_defaults();
423

    
424
		$keys = array(
425
		    'latencylow',
426
		    'latencyhigh',
427
		    'losslow',
428
		    'losshigh'
429
		);
430

    
431
		/* Replace default values by user-defined */
432
		foreach ($keys as $key) {
433
			if (isset($gw[$key]) && is_numeric($gw[$key])) {
434
				$settings[$key] = $gw[$key];
435
			}
436
		}
437

    
438
		if ($r['latency_avg'] > $settings['latencyhigh']) {
439
			if (!$action_disable) {
440
				$r['status'] = "down";
441
			}
442
			$r['substatus'] = "highdelay";
443
		} else if ($r['loss'] > $settings['losshigh']) {
444
			if (!$action_disable) {
445
				$r['status'] = "down";
446
			}
447
			$r['substatus'] = "highloss";
448
		} else if ($r['latency_avg'] > $settings['latencylow']) {
449
			$r['substatus'] = "delay";
450
		} else if ($r['loss'] > $settings['losslow']) {
451
			$r['substatus'] = "loss";
452
		}
453
	}
454

    
455
	return $r;
456
}
457

    
458
/* return the status of the dpinger targets as an array */
459
function return_gateways_status($byname = false, $gways = false) {
460
	global $config, $g;
461

    
462
	$dpinger_gws = running_dpinger_processes();
463
	$status = array();
464

    
465
	if (is_array($gways)) {
466
		$gateways_arr = $gways;
467
	} else {
468
		$gateways_arr = return_gateways_array();
469
	}
470

    
471
	foreach ($dpinger_gws as $gwname => $gwdata) {
472
		/*
473
		 * If action is disabled for this gateway, then we want a
474
		 * detailed status.  That reports "highdelay" or "highloss"
475
		 * rather than just "down".  Because reporting the gateway
476
		 * down would be misleading (gateway action is disabled)
477
		 */
478
		$action_disable = $gateways_arr[$gwname]['action_disable'];
479
		$dpinger_status = get_dpinger_status($gwname, $action_disable);
480
		if ($dpinger_status === false) {
481
			continue;
482
		}
483

    
484
		if ($byname == false) {
485
			$target = $dpinger_status['targetip'];
486
		} else {
487
			$target = $gwname;
488
		}
489

    
490
		$status[$target] = array();
491
		$status[$target]['monitorip'] = $dpinger_status['targetip'];
492
		$status[$target]['srcip'] = $dpinger_status['srcip'];
493
		$status[$target]['name'] = $gwname;
494
		$status[$target]['delay'] =
495
		    empty($dpinger_status['latency_avg'])
496
		    ? "0ms"
497
		    : $dpinger_status['latency_avg'] . "ms";
498
		$status[$target]['stddev'] =
499
		    empty($dpinger_status['latency_stddev'])
500
		    ? "0ms"
501
		    : $dpinger_status['latency_stddev'] . "ms";
502
		$status[$target]['loss'] = empty($dpinger_status['loss'])
503
		    ? "0.0%"
504
		    : round($dpinger_status['loss'], 1) . "%";
505
		$status[$target]['status'] = $dpinger_status['status'];
506
		$status[$target]['substatus'] = $dpinger_status['substatus'];
507
	}
508

    
509
	/* tack on any gateways that have monitoring disabled
510
	 * or are down, which could cause gateway groups to fail */
511
	$gateways_arr = return_gateways_array();
512
	foreach ($gateways_arr as $gwitem) {
513
		if (!isset($gwitem['monitor_disable'])) {
514
			continue;
515
		}
516
		if (!is_ipaddr($gwitem['monitor'])) {
517
			$realif = $gwitem['interface'];
518
			$tgtip = get_interface_gateway($realif);
519
			if (!is_ipaddr($tgtip)) {
520
				$tgtip = "none";
521
			}
522
			$srcip = find_interface_ip($realif);
523
		} else {
524
			$tgtip = $gwitem['monitor'];
525
			$srcip = find_interface_ip($realif);
526
		}
527
		if ($byname == true) {
528
			$target = $gwitem['name'];
529
		} else {
530
			$target = $tgtip;
531
		}
532

    
533
		/* failsafe for down interfaces */
534
		if ($target == "none") {
535
			$target = $gwitem['name'];
536
			$status[$target]['name'] = $gwitem['name'];
537
			$status[$target]['delay'] = "0.0ms";
538
			$status[$target]['loss'] = "100.0%";
539
			$status[$target]['status'] = "down";
540
			$status[$target]['substatus'] = "down";
541
		} else {
542
			$status[$target]['monitorip'] = $tgtip;
543
			$status[$target]['srcip'] = $srcip;
544
			$status[$target]['name'] = $gwitem['name'];
545
			$status[$target]['delay'] = "";
546
			$status[$target]['loss'] = "";
547
			$status[$target]['status'] = "online";
548
			$status[$target]['substatus'] = "none";
549
		}
550

    
551
		$status[$target]['monitor_disable'] = true;
552
	}
553
	return($status);
554
}
555

    
556
function return_gateways_status_text($byname = false, $brief = false) {
557
	$gwstat = return_gateways_status($byname);
558
	$output = "";
559
	$widths = array();
560
	$col_sep = 2;
561
	if ($brief) {
562
		$collist = array('status' => "Status");
563
	} else {
564
		$collist = array('monitorip' => "Monitor",
565
				'srcip' => "Source",
566
				'delay' => "Delay",
567
				'stddev' => "StdDev",
568
				'loss' => "Loss",
569
				'status' => "Status",
570
				'substatus' => "Substatus");
571
	}
572
	foreach ($gwstat as $gw) {
573
		foreach ($gw as $gwdidx => $gwdata) {
574
			if (strlen($gwdata) > $widths[$gwdidx]) {
575
				$widths[$gwdidx] = strlen($gwdata);
576
			}
577
		}
578
	}
579

    
580
	$output .= str_pad("Name", $widths['name'] + $col_sep, " ", STR_PAD_RIGHT);
581
	foreach ($collist as $hdrcol => $hdrdesc) {
582
		if (strlen($hdrdesc) > $widths[$hdrcol]) {
583
			$widths[$hdrcol] = strlen($hdrdesc);
584
		}
585
		$output .= str_pad($hdrdesc, $widths[$hdrcol] + $col_sep, " ", (substr($hdrcol, -2, 2) == "ip") ? STR_PAD_RIGHT : STR_PAD_LEFT);
586
	}
587
	$output .= "\n";
588

    
589
	foreach ($gwstat as $idx => $gw) {
590
		$output .= str_pad($gw['name'], $widths['name'] + $col_sep, " ", STR_PAD_RIGHT);
591
		foreach (array_keys($collist) as $col) {
592
			$output .= str_pad($gw[$col], $widths[$col] + $col_sep, " ", (substr($col, -2, 2) == "ip") ? STR_PAD_RIGHT : STR_PAD_LEFT);
593
		}
594
		$output .= "\n";
595
	}
596

    
597
	return $output;
598
}
599

    
600
function compare_gateway_order_configured($a, $b) {
601
	/* XXX WAN always has precedence */
602
	if ($a['friendlyiface'] == "wan") {
603
		return -1;
604
	} elseif ($b['friendlyiface'] == "wan") {
605
		return 1;
606
	}
607

    
608
	if ($a['attribute'] === $b['attribute']) {
609
		if ($a['attribute'] === 'system') {
610
			$res = (($a['name'] < $b['name'])) ? -1 : 1;
611
			return $res;
612
		}
613
		return 0;
614
	}
615
	if ($a['attribute'] === 'system' || $b['attribute'] === 'system') {
616
		$res = (($b['attribute'] === 'system')) ? -1 : 1;
617
		return $res;
618
	}
619
	$res = ($a['attribute'] < $b['attribute']) ? -1 : 1;
620
	return $res;
621
}
622

    
623
function order_gateways_as_configured($gateways_arr) {
624
	uasort($gateways_arr, 'compare_gateway_order_configured');
625
	return $gateways_arr;
626
}
627

    
628
/* Return all configured gateways on the system
629
   $disabled = true - include gateways that are disabled
630
   $localhost = true - include "Null" entries for localhost IP addresses
631
   $inactive = true - include gateways on inactive interfaces
632
   $integer_index = true - index the returned array by integers 0,1,2,... instead of by GW name
633
*/
634
function return_gateways_array($disabled = false, $localhost = false, $inactive = false, $integer_index = false) {
635
	global $config, $g;
636

    
637
	$gateways_arr = array();
638
	$gateways_arr_temp = array();
639
	$cgw4 = route_get_default('inet');
640
	$cgw6 = route_get_default('inet6');
641
	$found_defaultv4 = 0;
642
	$found_defaultv6 = 0;
643

    
644
	// Ensure the interface cache is up to date first
645
	$interfaces = get_interface_arr(true);
646

    
647
	$i = -1;
648
	/* Process/add all the configured gateways. */
649
	if (is_array($config['gateways']) && is_array($config['gateways']['gateway_item'])) {
650
		foreach ($config['gateways']['gateway_item'] as $gateway) {
651
			if (!is_array($gateway) || empty($gateway)) {
652
				continue;
653
			}
654

    
655
			/* Increment it here to do not skip items */
656
			$i++;
657
			if (isset($gateway['defaultgw'])) {
658
				unset($gateway['defaultgw']);
659
			}
660

    
661
			if (empty($config['interfaces'][$gateway['interface']])) {
662
				if ($inactive === false) {
663
					continue;
664
				} else {
665
					$gateway['inactive'] = true;
666
				}
667
			}
668
			$wancfg = $config['interfaces'][$gateway['interface']];
669

    
670
			/* skip disabled interfaces */
671
			if ($disabled === false && (!isset($wancfg['enable']))) {
672
				continue;
673
			}
674

    
675
			/* if the gateway is dynamic and we can find the IPv4, Great! */
676
			if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") {
677
				if ($gateway['ipprotocol'] == "inet") {
678
					/* we know which interfaces is dynamic, this should be made a function */
679
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
680
					/* no IP address found, set to dynamic */
681
					if (!is_ipaddrv4($gateway['gateway'])) {
682
						$gateway['gateway'] = "dynamic";
683
					}
684
					$gateway['dynamic'] = true;
685
				}
686

    
687
				/* if the gateway is dynamic and we can find the IPv6, Great! */
688
				else if ($gateway['ipprotocol'] == "inet6") {
689
					/* we know which interfaces is dynamic, this should be made a function, and for v6 too */
690
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
691
					/* no IPv6 address found, set to dynamic */
692
					if (!is_ipaddrv6($gateway['gateway'])) {
693
						$gateway['gateway'] = "dynamic";
694
					}
695
					$gateway['dynamic'] = true;
696
				}
697
			} else {
698
				/* getting this detection right is hard at this point because we still don't
699
				 * store the address family in the gateway item */
700
				if (is_ipaddrv4($gateway['gateway'])) {
701
					$gateway['ipprotocol'] = "inet";
702
				} else if (is_ipaddrv6($gateway['gateway'])) {
703
					$gateway['ipprotocol'] = "inet6";
704
				}
705
			}
706

    
707
			if (isset($gateway['monitor_disable'])) {
708
				$gateway['monitor_disable'] = true;
709
			} else if (empty($gateway['monitor'])) {
710
				$gateway['monitor'] = $gateway['gateway'];
711
			}
712

    
713
			if (isset($gateway['action_disable'])) {
714
				$gateway['action_disable'] = true;
715
			}
716

    
717
			$gateway['friendlyiface'] = $gateway['interface'];
718
			$gateway['friendlyifdescr'] = convert_friendly_interface_to_friendly_descr($gateway['interface']);
719

    
720
			/* special treatment for tunnel interfaces */
721
			if ($gateway['ipprotocol'] == "inet6") {
722
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet6", false, false);
723
			} else {
724
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet", false, false);
725
			}
726

    
727
			if ($gateway['ipprotocol'] == "inet" &&
728
					($gateway['gateway'] == $cgw4)) {
729
				$gateway['isdefaultgw'] = true;
730
				$found_defaultv4 = 1;
731
			} else if ($gateway['ipprotocol'] == "inet6" &&
732
					($gateway['gateway'] == $cgw6)) {
733
				$gateway['isdefaultgw'] = true;
734
				$found_defaultv6 = 1;
735
			}
736
			/* include the gateway index as the attribute */
737
			$gateway['attribute'] = $i;
738

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

    
743
			/* skip disabled gateways if the caller has not asked for them to be returned. */
744
			if (!($disabled === false && isset($gateway['disabled']))) {
745
				$gateways_arr[$gateway['name']] = $gateway;
746
			}
747
		}
748
	}
749
	unset($gateway);
750

    
751
	//Sort the array by GW name before moving on.
752
	ksort($gateways_arr, SORT_STRING | SORT_FLAG_CASE);
753

    
754
	/* Loop through all interfaces with a gateway and add it to a array */
755
	if ($disabled == false) {
756
		$iflist = get_configured_interface_with_descr();
757
	} else {
758
		$iflist = get_configured_interface_with_descr(true);
759
	}
760

    
761
	/* Process/add dynamic v4 gateways. */
762
	foreach ($iflist as $ifname => $friendly) {
763
		if (!interface_has_gateway($ifname)) {
764
			continue;
765
		}
766

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

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

    
776
		if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) {
777
			continue;
778
		}
779

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

    
862
		$gateway = array();
863
		$gateway['dynamic'] = false;
864
		$gateway['ipprotocol'] = "inet";
865
		$gateway['gateway'] = get_interface_gateway($ifname, $gateway['dynamic']);
866
		$gateway['interface'] = get_real_interface($ifname);
867
		$gateway['friendlyiface'] = $ifname;
868
		$gateway['friendlyifdescr'] = convert_friendly_interface_to_friendly_descr($ifname);
869
		$gateway['name'] = "{$friendly}{$ctype}";
870
		$gateway['attribute'] = "system";
871

    
872
		if (($gateway['dynamic'] === "default") && ($found_defaultv4 == 0)) {
873
			$gateway['isdefaultgw'] = true;
874
			$gateway['dynamic'] = true;
875
			$found_defaultv4 = 1;
876
		}
877

    
878
		/* Loopback dummy for dynamic interfaces without a IP */
879
		if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) {
880
			$gateway['gateway'] = "dynamic";
881
		}
882

    
883
		/* automatically skip known static and dynamic gateways that were previously processed */
884
		foreach ($gateways_arr_temp as $gateway_item) {
885
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
886
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
887
				continue 2;
888
			}
889
		}
890

    
891
		if (is_ipaddrv4($gateway['gateway'])) {
892
			$gateway['monitor'] = $gateway['gateway'];
893
		}
894

    
895
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
896
		$gateways_arr[$gateway['name']] = $gateway;
897
	}
898
	unset($gateway);
899

    
900
	/* Process/add dynamic v6 gateways. */
901
	foreach ($iflist as $ifname => $friendly) {
902
		/* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */
903
		if (!isset($config['system']['ipv6allow'])) {
904
			break;
905
		}
906

    
907
		if (!interface_has_gatewayv6($ifname)) {
908
			continue;
909
		}
910

    
911
		if (empty($config['interfaces'][$ifname])) {
912
			continue;
913
		}
914

    
915
		$ifcfg = &$config['interfaces'][$ifname];
916
		if (!isset($ifcfg['enable'])) {
917
			continue;
918
		}
919

    
920
		if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) {
921
			continue;
922
		}
923

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

    
1005
		$gateway = array();
1006
		$gateway['dynamic'] = false;
1007
		$gateway['ipprotocol'] = "inet6";
1008
		$gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']);
1009
		$gateway['interface'] = get_real_interface($ifname, "inet6");
1010
		switch ($ifcfg['ipaddrv6']) {
1011
			case "6rd":
1012
			case "6to4":
1013
				$gateway['dynamic'] = "default";
1014
				break;
1015
		}
1016
		$gateway['friendlyiface'] = $ifname;
1017
		$gateway['friendlyifdescr'] = convert_friendly_interface_to_friendly_descr($ifname);
1018
		$gateway['name'] = "{$friendly}{$ctype}";
1019
		$gateway['attribute'] = "system";
1020

    
1021
		if (($gateway['dynamic'] === "default") && ($found_defaultv6 == 0)) {
1022
			$gateway['isdefaultgw'] = true;
1023
			$gateway['dynamic'] = true;
1024
			$found_defaultv6 = 1;
1025
		}
1026

    
1027
		/* Loopback dummy for dynamic interfaces without a IP */
1028
		if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) {
1029
			$gateway['gateway'] = "dynamic";
1030
		}
1031

    
1032
		/* automatically skip known static and dynamic gateways that were previously processed */
1033
		foreach ($gateways_arr_temp as $gateway_item) {
1034
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
1035
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
1036
				continue 2;
1037
			}
1038
		}
1039

    
1040
		if (is_ipaddrv6($gateway['gateway'])) {
1041
			$gateway['monitor'] = $gateway['gateway'];
1042
		}
1043

    
1044
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
1045
		$gateways_arr[$gateway['name']] = $gateway;
1046
	}
1047
	unset($gateway);
1048

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

    
1070
	if ($localhost === true) {
1071
		/* attach localhost for Null routes */
1072
		$gwlo4 = array();
1073
		$gwlo4['name'] = "Null4";
1074
		$gwlo4['interface'] = "lo0";
1075
		$gwlo4['ipprotocol'] = "inet";
1076
		$gwlo4['gateway'] = "127.0.0.1";
1077
		$gwlo4['attribute'] = "system";
1078
		$gwlo6 = array();
1079
		$gwlo6['name'] = "Null6";
1080
		$gwlo6['interface'] = "lo0";
1081
		$gwlo6['ipprotocol'] = "inet6";
1082
		$gwlo6['gateway'] = "::1";
1083
		$gwlo6['attribute'] = "system";
1084
		$gateways_arr['Null4'] = $gwlo4;
1085
		$gateways_arr['Null6'] = $gwlo6;
1086
	}
1087

    
1088
	if ($integer_index) {
1089
		$gateways_arr = array_values($gateways_arr);
1090
	}
1091

    
1092
	if ($found_defaultv4 != 1 && is_ipaddr($cgw4)) {
1093
		foreach($gateways_arr as &$gw) {
1094
			if ($gw['gateway'] == $cgw4) {
1095
				$gw['isdefaultgw'] = true;
1096
			}
1097
		}
1098
	}
1099
	if ($found_defaultv6 != 1 && is_ipaddr($cgw6)) {
1100
		foreach($gateways_arr as &$gw) {
1101
			if ($gw['gateway'] == $cgw6) {
1102
				$gw['isdefaultgw'] = true;
1103
			}
1104
		}
1105
	}
1106

    
1107
	$gways = order_gateways_as_configured($gateways_arr);
1108

    
1109
	// Add the tier names here so that system_gateways.php doesn't need to
1110
	foreach ($gways as $idx => $gway) {
1111
		$gways[$idx]['tiername'] = gateway_getgwtiername($gways, $idx);
1112
	}
1113

    
1114
	return $gways;
1115
}
1116

    
1117
function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
1118
	global $config, $g;
1119
	/*
1120
	 * NOTE: The code below is meant to replace the default gateway when it goes down.
1121
	 *	This facilitates services running on pfSense itself and are not handled by a PBR to continue working.
1122
	 */
1123
	$set_dfltgwname = '';
1124

    
1125
	if ($ipprotocol == 'inet') {
1126
		$gwdefault = $config['gateways']['defaultgw4'];
1127
	} else {
1128
		$gwdefault = $config['gateways']['defaultgw6'];
1129
	}
1130
	/* do not delete dynamic (frr/bgp/ospf) route
1131
	 * see https://redmine.pfsense.org/issues/12536 */
1132
	if ($gwdefault == "-") {
1133
		if (is_static_route('default', $ipprotocol)) {
1134
			route_del('default', $ipprotocol); 
1135
		}
1136
		return;
1137
	}
1138
	if (isset($gateways_arr[$gwdefault])) {
1139
		// the configured gateway is a regular one. (not a gwgroup) use it as is..
1140
		$set_dfltgwname = $gwdefault;
1141
	} elseif (empty($gwdefault)) {
1142
		// 'automatic' mode, pick the first one thats 'up' or 'unmonitored' which is always considered up
1143
		$gateways_arr = order_gateways_as_configured($gateways_arr);
1144
		$fallback = "";
1145
		foreach($gateways_arr as $gwname => $gwsttng) {
1146
			if (($gwsttng['ipprotocol'] != $ipprotocol) || isset($gwsttng['force_down'])) {
1147
				continue;
1148
			}
1149

    
1150
			if (isset($gwsttng['monitor_disable']) || isset($gwsttng['action_disable']) ||
1151
			    ($gateways_status[$gwname]['status'] == "online")) {
1152
				$set_dfltgwname = $gwname;
1153
				break;
1154
			}
1155
			if (empty($fallback) && $gwsttng['interface'] != 'lo0') {
1156
				$fallback = $gwname;
1157
			}
1158
		}
1159
		if (empty($set_dfltgwname) && !empty($fallback)) {
1160
			log_error(sprintf("Gateway, none 'available' for %s, use the first one configured. '%s'", $ipprotocol, $fallback));
1161
			$set_dfltgwname = $fallback;
1162
		} else {
1163
			log_error("Gateway, NONE AVAILABLE");
1164
		}
1165
	} else {
1166
		// a gwgroup is selected
1167
		// find the best available gateway given options available..
1168
		$gwg_members = array();
1169
		$viplist = get_configured_vip_list();
1170
		if (is_array($config['gateways']['gateway_group'])) {
1171
			foreach ($config['gateways']['gateway_group'] as $group) {
1172
				if ($group['name'] == $gwdefault) {
1173
					// finds the gw members of the best available tier for this group.
1174
					$gwg_members = get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1175
				}
1176
			}
1177
		}
1178

    
1179
		if (count($gwg_members) > 0) {
1180
			$currentdefaultgwip = route_get_default($ipprotocol);
1181
			$found_current = false;
1182
			foreach($gwg_members as $gwgroupitem) {
1183
				if (!empty($currentdefaultgwip) && ($gwgroupitem['gwip'] == $currentdefaultgwip)) {
1184
					$set_dfltgwname = $gwgroupitem['gw'];
1185
					$found_current = true;
1186
					if (isset($config['system']['gw-debug'])) {
1187
						log_error("Keep current gateway, its already part of the group members.");
1188
					}
1189
					break;
1190
				}
1191
			}
1192
			if (!$found_current) {
1193
				$set_dfltgwname = $gwg_members[0]['gw'];
1194
				log_error(sprintf("Gateway, switch to: %s", $set_dfltgwname));
1195
			}
1196
		} else {
1197
			log_error("Gateway, NONE AVAILABLE");
1198
		}
1199
	}
1200
	if (!empty($set_dfltgwname) && isset($gateways_arr[$set_dfltgwname])) {
1201
		setdefaultgateway($gateways_arr[$set_dfltgwname]);
1202
	} elseif (empty($set_dfltgwname)) {
1203
		route_del('default', $ipprotocol); 
1204
	}
1205
}
1206

    
1207
function setdefaultgateway($gw) {
1208
	global $g, $config;
1209
	if (isset($config['system']['route-debug'])) {
1210
		file_put_contents("/dev/console", "\n[".getmypid()."] SET DEF GW: {$gw['name']}");
1211
	}
1212
	$ipprotocol = $gw['ipprotocol'];
1213
	if ($gw['gateway'] == "dynamic") {
1214
		if ($ipprotocol == 'inet') {
1215
			$gw['gateway'] = get_interface_gateway($gw['friendlyiface']);
1216
		} else {
1217
			$gw['gateway'] = get_interface_gateway_v6($$gw['friendlyiface']);
1218
		}
1219
	}
1220
	if ($ipprotocol == 'inet6' && !is_ipaddrv6($gw['gateway'])) {
1221
		return;
1222
	}
1223
	if ($ipprotocol == 'inet' && !is_ipaddrv4($gw['gateway'])) {
1224
		return;
1225
	}
1226
	if ($ipprotocol == 'inet6') {
1227
		if (is_linklocal($gw['gateway']) && get_ll_scope($gw['gateway']) == '') {
1228
			$gw['gateway'] .= "%" . $gw['interface'];
1229
		}
1230
	}
1231
	$currentdefaultgwip = route_get_default($ipprotocol);
1232
	if ($currentdefaultgwip != $gw['gateway']) {
1233
		log_error("Default gateway setting {$gw['descr']} as default.");
1234

    
1235
		if ($ipprotocol == 'inet') {
1236
			$inet = '';
1237
		} else {
1238
			$inet = 'v6';
1239
		}
1240
		unlink_if_exists("{$g['tmp_path']}/*_defaultgw{$inet}");
1241
		$defaultif = get_real_interface($gw['interface']);
1242
		if ($defaultif) {
1243
			@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw{$inet}", $gw['gateway']);
1244
		}
1245

    
1246
		if (isset($gw["nonlocalgateway"])) {
1247
			if (is_ipaddr($gw['gateway']) && !empty($gw['interface'])) {
1248
				route_add_or_change($gw['gateway'], '',
1249
				    $gw['interface']);
1250
			}
1251
		}
1252
		if (isset($config['system']['route-debug'])) {
1253
			file_put_contents("/dev/console", "\n[".getmypid()."] SET DEF GW: {$gw['name']} ({$gw['gateway']})");
1254
		}
1255
		route_add_or_change("default", $gw['gateway'], '', '',
1256
		    $ipprotocol);
1257
		return true;
1258
	}
1259
}
1260

    
1261
function get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist){
1262
	$result = array();
1263
	/* create array with group gateways members separated by tier */
1264
	$tiers = array();
1265
	$backupplan = array();
1266
	$gwvip_arr = array();
1267
	foreach ($group['item'] as $item) {
1268
		list($gwname, $tier, $vipname) = explode("|", $item);
1269

    
1270
		if (is_ipaddr($viplist[$vipname])) {
1271
			if (!is_array($gwvip_arr[$group['name']])) {
1272
				$gwvip_arr[$group['name']] = array();
1273
			}
1274
			$gwvip_arr[$group['name']][$gwname] = $vipname;
1275
		}
1276

    
1277
		/* Do it here rather than reiterating again the group in case no member is up. */
1278
		if (!is_array($backupplan[$tier])) {
1279
			$backupplan[$tier] = array();
1280
		}
1281
		$backupplan[$tier][] = $gwname;
1282

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

    
1348
	/* we do not really foreach the tiers as we stop after the first tier */
1349
	foreach ($tiers as $tieridx => $tier) {
1350
		/* process all gateways in this tier */
1351
		foreach ($tier as $member) {
1352
			/* determine interface gateway */
1353
			if (isset($gateways_arr[$member])) {
1354
				$gateway = $gateways_arr[$member];
1355
				$int = $gateway['interface'];
1356
				$gatewayip = "";
1357
				if (is_ipaddr($gateway['gateway'])) {
1358
					$gatewayip = $gateway['gateway'];
1359
				} elseif (!empty($int)) {
1360
					if ($gateway['ipprotocol'] == 'inet') {
1361
						$gatewayip = get_interface_gateway($gateway['friendlyiface']);
1362
					} else {
1363
						$gatewayip = get_interface_gateway_v6($gateway['friendlyiface']);
1364
					}
1365
				}
1366

    
1367
				if (!empty($int)) {
1368
					$result['ipprotocol'] = $gateway['ipprotocol'];
1369
					if (is_ipaddr($gatewayip)) {
1370
						$groupmember = array();
1371
						$groupmember['gw'] = $member;
1372
						$groupmember['int'] = $int;
1373
						$groupmember['gwip'] = $gatewayip;
1374
						/* set correct linklocal gateway address,
1375
						 * see https://redmine.pfsense.org/issues/12721 */
1376
						if (is_ipaddrv6($gatewayip) && is_linklocal($gatewayip) && empty(get_ll_scope($gatewayip))) {
1377
							$groupmember['gwip'] .= '%' . $int;
1378
						}
1379
						$groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1;
1380
						if (is_array($gwvip_arr[$group['name']]) && !empty($gwvip_arr[$group['name']][$member])) {
1381
							$groupmember['vip'] = $gwvip_arr[$group['name']][$member];
1382
						}
1383
						$result[] = $groupmember;
1384
					}
1385
				}
1386
			}
1387
		}
1388
		/* we should have the 1st available tier now, exit stage left */
1389
		if (count($result) > 0) {
1390
			break;
1391
		} else {
1392
			log_error(sprintf(gettext('GATEWAYS: Group %1$s did not have any gateways up on tier %2$s!'), $group['name'], $tieridx));
1393
		}
1394
	}
1395
	// Add description field last to not influence the count() above
1396
	$result['descr'] = $group['descr'];
1397
	return $result;
1398
}
1399

    
1400
function get_gwgroup_members($groupname) {
1401
	global $config;
1402
	$gateways_status = return_gateways_status(true);
1403
	$gateways_arr = return_gateways_array();
1404
	$viplist = get_configured_vip_list();
1405
	foreach ($config['gateways']['gateway_group'] as $group) {
1406
		if ($group['name'] == $groupname) {
1407
			return get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1408
		}
1409
	}
1410
	return array();
1411
}
1412

    
1413
/*
1414
 * Return an array with all gateway groups with name as key
1415
 * All gateway groups will be processed before returning the array.
1416
 */
1417
function return_gateway_groups_array($fixup = false, $gways = false) {
1418
	global $config;
1419

    
1420
	/* fetch the current gateways status */
1421
	if (is_array($gways)) {
1422
		$gateways_status = $gways;
1423
	} else {
1424
		$gateways_status = return_gateways_status(true);
1425
	}
1426

    
1427
	$gateways_arr = return_gateways_array();
1428
	$gateway_groups_array = array();
1429
	if ($fixup == true) {
1430
		$gw4 = lookup_gateway_or_group_by_name($config['gateways']['defaultgw4'], $gways);
1431
		$gw6 = lookup_gateway_or_group_by_name($config['gateways']['defaultgw6'], $gways);
1432
		if ($gw4 && $gw4['type'] == 'gatewaygroup') {
1433
			fixup_default_gateway("inet", $gateways_status, $gateways_arr);
1434
		}
1435
		if ($gw6 && $gw6['type'] == 'gatewaygroup') {
1436
			fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
1437
		}
1438
	}
1439
	init_config_arr(array('gateways', 'gateway_group'));
1440
	if (!empty($config['gateways']['gateway_group'])) {
1441
		$viplist = get_configured_vip_list();
1442
		foreach ($config['gateways']['gateway_group'] as $group) {
1443
			$gateway_groups_array[$group['name']] = get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1444
		}
1445
	}
1446

    
1447
	return ($gateway_groups_array);
1448
}
1449

    
1450
/* Update DHCP WAN Interface ip address in gateway group item */
1451
function dhclient_update_gateway_groups_defaultroute($interface = "wan") {
1452
	global $config;
1453

    
1454
	if (is_array($config['gateways']['gateway_item'])) {
1455
		foreach ($config['gateways']['gateway_item'] as & $gw) {
1456
			if ($gw['interface'] != $interface) {
1457
				continue;
1458
			}
1459

    
1460
			$current_gw = get_interface_gateway($interface);
1461
			if ($gw['gateway'] <> $current_gw) {
1462
				$gw['gateway'] = $current_gw;
1463
				$changed = true;
1464
			}
1465
		}
1466
	}
1467

    
1468
	if ($changed && $current_gw) {
1469
		write_config(sprintf(gettext(
1470
		    'Updating gateway group gateway for %1$s - new gateway is %2$s'),
1471
		    $interface, $current_gw));
1472
	}
1473
}
1474

    
1475
function lookup_gateway_or_group_by_name($gwname, $gways = false) {
1476
	global $config;
1477

    
1478
	if (is_array($gways)) {
1479
		$gateways_arr = $gways;
1480
	} else {
1481
		$gateways_arr = return_gateways_array();
1482
	}
1483

    
1484
	foreach ($gateways_arr as $gw) {
1485
		if ($gw['name'] == $gwname) {
1486
			$gw['type'] = 'gateway';
1487
			return $gw;
1488
		}
1489
	}
1490

    
1491
	init_config_arr(array('gateways', 'gateway_group'));
1492
	foreach ($config['gateways']['gateway_group'] as $gwg) {
1493
		if ($gwg['name'] == $gwname) {
1494
			$gwg['type'] = 'gatewaygroup';
1495
			return $gwg;
1496
		}
1497
	}
1498

    
1499
	return false;
1500
}
1501

    
1502
function lookup_gateway_ip_by_name($name, $disabled = false) {
1503

    
1504
	$gateways_arr = return_gateways_array($disabled, true);
1505
	foreach ($gateways_arr as $gname => $gw) {
1506
		if ($gw['name'] === $name || $gname === $name) {
1507
			return $gw['gateway'];
1508
		}
1509
	}
1510

    
1511
	return false;
1512
}
1513

    
1514
function lookup_gateway_monitor_ip_by_name($name) {
1515

    
1516
	$gateways_arr = return_gateways_array(false, true);
1517
	if (!empty($gateways_arr[$name])) {
1518
		$gateway = $gateways_arr[$name];
1519
		if (!is_ipaddr($gateway['monitor'])) {
1520
			return $gateway['gateway'];
1521
		}
1522

    
1523
		return $gateway['monitor'];
1524
	}
1525

    
1526
	return (false);
1527
}
1528

    
1529
function lookup_gateway_interface_by_name($name) {
1530

    
1531
	$gateways_arr = return_gateways_array(false, true);
1532
	if (!empty($gateways_arr[$name])) {
1533
		$interfacegw = $gateways_arr[$name]['friendlyiface'];
1534
		return ($interfacegw);
1535
	}
1536

    
1537
	return (false);
1538
}
1539

    
1540
function get_root_interface($interface) {
1541
	if (substr($interface, 0, 4) == '_vip') {
1542
		$interface = get_configured_vip_interface($interface);
1543
		if (substr($interface, 0, 4) == '_vip') {
1544
			$interface = get_configured_vip_interface($interface);
1545
		}
1546
	}
1547
	return $interface;
1548
}
1549

    
1550
function get_interface_gateway($interface, &$dynamic = false) {
1551
	global $config, $g;
1552

    
1553
	$interface = get_root_interface($interface);
1554

    
1555
	$gw = NULL;
1556
	$gwcfg = $config['interfaces'][$interface];
1557
	if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) {
1558
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1559
			if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
1560
				$gw = $gateway['gateway'];
1561
				break;
1562
			}
1563
		}
1564
	}
1565

    
1566
	// for dynamic interfaces we handle them through the $interface_router file.
1567
	if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) {
1568
		$realif = get_real_interface($interface);
1569
		if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
1570
			$gw = trim(@file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
1571
			$dynamic = true;
1572
		}
1573
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) {
1574
			$dynamic = "default";
1575
		}
1576

    
1577
	}
1578

    
1579
	/* return gateway */
1580
	return ($gw);
1581
}
1582

    
1583
function get_interface_gateway_last($interface, $family = 'inet') {
1584
	global $config, $g;
1585
	$interface = get_root_interface($interface);
1586
	$realif = get_real_interface($interface);
1587
	$suffix = ($family == 'inet6') ? 'v6' : '';
1588
	if (file_exists("{$g['tmp_path']}/{$realif}_router{$suffix}.last")) {
1589
		return trim(@file_get_contents("{$g['tmp_path']}/{$realif}_router{$suffix}.last"), " \n");
1590
	}
1591
	return '';
1592
}
1593

    
1594
function get_interface_gateway_v6($interface, &$dynamic = false) {
1595
	global $config, $g;
1596

    
1597
	$interface = get_root_interface($interface);
1598

    
1599
	$gw = NULL;
1600
	$gwcfg = $config['interfaces'][$interface];
1601
	if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) {
1602
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1603
			if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
1604
				$gw = $gateway['gateway'];
1605
				break;
1606
			}
1607
		}
1608
	}
1609

    
1610
	// for dynamic interfaces we handle them through the $interface_router file.
1611
	if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) {
1612
		$realif = get_real_interface($interface);
1613
		if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
1614
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
1615
			$dynamic = true;
1616
		}
1617
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) {
1618
			$dynamic = "default";
1619
		}
1620
	}
1621
	/* return gateway */
1622
	return ($gw);
1623
}
1624

    
1625
/* Check a IP address against a gateway IP or name
1626
 * to verify it's address family */
1627
function validate_address_family($ipaddr, $gwname, $disabled = false) {
1628
	$v4ip = false;
1629
	$v6ip = false;
1630
	$v4gw = false;
1631
	$v6gw = false;
1632

    
1633
	if (is_ipaddrv4($ipaddr)) {
1634
		$v4ip = true;
1635
	}
1636
	if (is_ipaddrv6($ipaddr)) {
1637
		$v6ip = true;
1638
	}
1639
	if (is_ipaddrv4($gwname)) {
1640
		$v4gw = true;
1641
	}
1642
	if (is_ipaddrv6($gwname)) {
1643
		$v6gw = true;
1644
	}
1645

    
1646
	if ($v4ip && $v4gw) {
1647
		return true;
1648
	}
1649
	if ($v6ip && $v6gw) {
1650
		return true;
1651
	}
1652

    
1653
	/* still no match, carry on, lookup gateways */
1654
	if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname, $disabled))) {
1655
		$v4gw = true;
1656
	}
1657
	if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname, $disabled))) {
1658
		$v6gw = true;
1659
	}
1660

    
1661
	$gw_array = return_gateways_array();
1662
	if (is_array($gw_array[$gwname])) {
1663
		switch ($gw_array[$gwname]['ipprotocol']) {
1664
			case "inet":
1665
				$v4gw = true;
1666
				break;
1667
			case "inet6":
1668
				$v6gw = true;
1669
				break;
1670
		}
1671
	}
1672

    
1673
	if ($v4ip && $v4gw) {
1674
		return true;
1675
	}
1676
	if ($v6ip && $v6gw) {
1677
		return true;
1678
	}
1679

    
1680
	return false;
1681
}
1682

    
1683
/* check if a interface is part of a gateway group */
1684
function interface_gateway_group_member($interface, $gwgroup_name = "") {
1685
	global $config;
1686

    
1687
	if (is_array($config['gateways']['gateway_group'])) {
1688
		$groups = $config['gateways']['gateway_group'];
1689
	} else {
1690
		return false;
1691
	}
1692

    
1693
	$gateways_arr = return_gateways_array(false, true);
1694
	foreach ($groups as $group) {
1695
		if (is_array($group['item'])) {
1696
			foreach ($group['item'] as $item) {
1697
				$elements = explode("|", $item);
1698
				$gwname = $elements[0];
1699
				if ($interface == $gateways_arr[$gwname]['interface'] &&
1700
				    (empty($gwgroup_name) || $gwgroup_name == $group['name'])) {
1701
					unset($gateways_arr);
1702
					return true;
1703
				}
1704
			}
1705
		}
1706
	}
1707
	unset($gateways_arr);
1708

    
1709
	return false;
1710
}
1711

    
1712
function gateway_is_gwgroup_member($name, $detail=false) {
1713
	global $config;
1714

    
1715
	if (is_array($config['gateways']['gateway_group'])) {
1716
		$groups = $config['gateways']['gateway_group'];
1717
	} else {
1718
		return false;
1719
	}
1720

    
1721
	$members = array();
1722
	foreach ($groups as $group) {
1723
		if (is_array($group['item'])) {
1724
			foreach ($group['item'] as $item) {
1725
				list($gwname, $tier, $vipname) = explode("|", $item);
1726
				if ($name == $gwname) {
1727
					if ($detail) {
1728
						$newitem = array();
1729
						$newitem['name'] = $group['name'];
1730
						$newitem['tier'] = $tier;
1731
						$newitem['vipname'] = $vipname;
1732
						$members[] = $newitem;
1733
					} else {
1734
						$members[] = $group['name'];
1735
					}
1736
				}
1737
			}
1738
		}
1739
	}
1740

    
1741
	return $members;
1742
}
1743
/*
1744
  Check the proposed gateway settings to see if they are valid.
1745
  $gateway_settings - the proposed array of proposed gateway settings
1746
  $id - the index of the gateway proposed to be modified (otherwise "" if adding a new gateway)
1747
  $parent_ip - the IP (v4 or v6) address about to be set on the corresponding interface (if any)
1748
  $parent_sn - the subnet about to be set on the corresponding interface (if any)
1749
  (Note: the above 2 parameters allow gateway parameters to be validated concurrently with saving
1750
   an interface, before the new interface parameters are actually saved in the config.)
1751
  Return completed $input_errors array if there is any problem.
1752
  Otherwise return an empty $input_errors array
1753
*/
1754
function validate_gateway($gateway_settings, $id = "", $parent_ip = "", $parent_sn = "") {
1755
	global $config, $gateway_state_kill_modes;
1756

    
1757
	$a_gateways = return_gateways_array(true, false, true, true);
1758
	$input_errors = array();
1759

    
1760
	/* input validation */
1761
	$reqdfields = explode(" ", "name interface");
1762
	$reqdfieldsn = array(gettext("Name"), gettext("Interface"));
1763

    
1764
	do_input_validation($gateway_settings, $reqdfields, $reqdfieldsn, $input_errors);
1765

    
1766
	if (!isset($gateway_settings['name'])) {
1767
		$input_errors[] = "A valid gateway name must be specified.";
1768
	}
1769
	if (!is_validaliasname($gateway_settings['name'])) {
1770
		$input_errors[] = invalidaliasnamemsg($gateway_settings['name'], gettext("gateway"));
1771
	} else if (isset($gateway_settings['disabled'])) {
1772
		// We have a valid gateway name that the user wants to mark as disabled.
1773
		// Check if the gateway name is used in any gateway group.
1774
		if (is_array($config['gateways']['gateway_group'])) {
1775
			foreach ($config['gateways']['gateway_group'] as $group) {
1776
				foreach ($group['item'] as $item) {
1777
					$items = explode("|", $item);
1778
					if ($items[0] == $gateway_settings['name']) {
1779
						$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']);
1780
					}
1781
				}
1782
			}
1783
		}
1784

    
1785
		// Check if the gateway name is used in any enabled Static Route.
1786
		if (is_array($config['staticroutes']['route'])) {
1787
			foreach ($config['staticroutes']['route'] as $route) {
1788
				if ($route['gateway'] == $gateway_settings['name']) {
1789
					if (!isset($route['disabled'])) {
1790
						// There is a static route that uses this gateway and is enabled (not disabled).
1791
						$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']);
1792
					}
1793
				}
1794
			}
1795
		}
1796

    
1797
		// Check if the gateway name is used by any DNS Server
1798
		$dnsgw_counter = 1;
1799
		while (isset($config["system"]["dns{$dnsgw_counter}gw"])) {
1800
			if ($gateway_settings['name'] == $config["system"]["dns{$dnsgw_counter}gw"]) {
1801
				// The user wants to disable this gateway, but there is a static route to the DNS server that refers to the gateway.
1802
				$input_errors[] = sprintf(gettext('Gateway "%1$s" cannot be disabled because it is in use by DNS Server "%2$s"'), $gateway_settings['name'], $config["system"]["dns{$dnsgw_counter}gw"]);
1803
			}
1804
			$dnsgw_counter++;
1805
		}
1806
	}
1807
	/* skip system gateways which have been automatically added */
1808
	if (($gateway_settings['gateway'] && (!is_ipaddr($gateway_settings['gateway'])) && ($gateway_settings['attribute'] !== "system")) && ($gateway_settings['gateway'] != "dynamic")) {
1809
		$input_errors[] = gettext("A valid gateway IP address must be specified.");
1810
	}
1811

    
1812
	if ($gateway_settings['gateway'] && is_ipaddr($gateway_settings['gateway'])) {
1813
		if (is_ipaddrv4($gateway_settings['gateway'])) {
1814
			if ($parent_ip == '') {
1815
				$parent_ip = get_interface_ip($gateway_settings['interface']);
1816
				$parent_sn = get_interface_subnet($gateway_settings['interface']);
1817
			}
1818
			if (empty($parent_ip) || empty($parent_sn)) {
1819
				$input_errors[] = gettext("Cannot add IPv4 Gateway Address because no IPv4 address could be found on the interface.");
1820
			} elseif (!isset($gateway_settings["nonlocalgateway"])) {
1821
				$subnets = array(gen_subnet($parent_ip, $parent_sn) . "/" . $parent_sn);
1822
				$vips = link_interface_to_vips($gateway_settings['interface']);
1823
				if (is_array($vips)) {
1824
					foreach ($vips as $vip) {
1825
						if (!is_ipaddrv4($vip['subnet'])) {
1826
							continue;
1827
						}
1828
						$subnets[] = gen_subnet($vip['subnet'], $vip['subnet_bits']) . "/" . $vip['subnet_bits'];
1829
					}
1830
				}
1831

    
1832
				$found = false;
1833
				foreach ($subnets as $subnet) {
1834
					if (ip_in_subnet($gateway_settings['gateway'], $subnet)) {
1835
						$found = true;
1836
						break;
1837
					}
1838
				}
1839

    
1840
				if ($found === false) {
1841
					$input_errors[] = sprintf(gettext("The gateway address %s does not lie within one of the chosen interface's subnets."), $gateway_settings['gateway']);
1842
				}
1843
			}
1844
		} else if (is_ipaddrv6($gateway_settings['gateway'])) {
1845
			/* do not do a subnet match on a link local address, it's valid */
1846
			if (!is_linklocal($gateway_settings['gateway'])) {
1847
				if ($parent_ip == '') {
1848
					$parent_ip = get_interface_ipv6($gateway_settings['interface']);
1849
					$parent_sn = get_interface_subnetv6($gateway_settings['interface']);
1850
				}
1851
				if (empty($parent_ip) || empty($parent_sn)) {
1852
					$input_errors[] = gettext("Cannot add IPv6 Gateway Address because no IPv6 address could be found on the interface.");
1853
				} elseif (!isset($gateway_settings["nonlocalgateway"])) {
1854
					$subnets = array(gen_subnetv6($parent_ip, $parent_sn) . "/" . $parent_sn);
1855
					$vips = link_interface_to_vips($gateway_settings['interface']);
1856
					if (is_array($vips)) {
1857
						foreach ($vips as $vip) {
1858
							if (!is_ipaddrv6($vip['subnet'])) {
1859
								continue;
1860
							}
1861
							$subnets[] = gen_subnetv6($vip['subnet'], $vip['subnet_bits']) . "/" . $vip['subnet_bits'];
1862
						}
1863
					}
1864

    
1865
					$found = false;
1866
					foreach ($subnets as $subnet) {
1867
						if (ip_in_subnet($gateway_settings['gateway'], $subnet)) {
1868
							$found = true;
1869
							break;
1870
						}
1871
					}
1872

    
1873
					if ($found === false) {
1874
						$input_errors[] = sprintf(gettext("The gateway address %s does not lie within one of the chosen interface's subnets."), $gateway_settings['gateway']);
1875
					}
1876
				}
1877
			}
1878
		}
1879

    
1880
		if (!empty($config['interfaces'][$gateway_settings['interface']]['ipaddr'])) {
1881
			if (is_ipaddr($config['interfaces'][$gateway_settings['interface']]['ipaddr']) && (empty($gateway_settings['gateway']) || $gateway_settings['gateway'] == "dynamic")) {
1882
				$input_errors[] = gettext("Dynamic gateway values cannot be specified for interfaces with a static IPv4 configuration.");
1883
			}
1884
		}
1885
		if (!empty($config['interfaces'][$gateway_settings['interface']]['ipaddrv6'])) {
1886
			if (is_ipaddr($config['interfaces'][$gateway_settings['interface']]['ipaddrv6']) && (empty($gateway_settings['gateway']) || $gateway_settings['gateway'] == "dynamic")) {
1887
				$input_errors[] = gettext("Dynamic gateway values cannot be specified for interfaces with a static IPv6 configuration.");
1888
			}
1889
		}
1890
	}
1891
	if (($gateway_settings['monitor'] != "") && ($gateway_settings['monitor'] != "dynamic")) {
1892
		validateipaddr($gateway_settings['monitor'], IPV4V6, "Monitor IP", $input_errors, false);
1893
	}
1894
	if (isset($gateway_settings['data_payload']) && is_numeric($gateway_settings['data_payload']) && $gateway_settings['data_payload'] < 0) {
1895
		$input_errors[] = gettext("A valid data payload must be specified.");
1896
	}
1897
	if (!empty($gateway_settings['skip_rules_gw_down']) && !array_key_exists($gateway_settings['skip_rules_gw_down'], $gateway_state_kill_modes)) {
1898
		$input_errors[] = gettext("Please select a valid State Killing on Gateway Failure mode.");
1899
	}
1900
	/* only allow correct IPv4 and IPv6 gateway addresses */
1901
	if (($gateway_settings['gateway'] <> "") && is_ipaddr($gateway_settings['gateway']) && $gateway_settings['gateway'] != "dynamic") {
1902
		if (is_ipaddrv6($gateway_settings['gateway']) && ($gateway_settings['ipprotocol'] == "inet")) {
1903
			$input_errors[] = sprintf(gettext("The IPv6 gateway address '%s' can not be used as a IPv4 gateway."), $gateway_settings['gateway']);
1904
		}
1905
		if (is_ipaddrv4($gateway_settings['gateway']) && ($gateway_settings['ipprotocol'] == "inet6")) {
1906
			$input_errors[] = sprintf(gettext("The IPv4 gateway address '%s' can not be used as a IPv6 gateway."), $gateway_settings['gateway']);
1907
		}
1908
	}
1909
	/* only allow correct IPv4 and IPv6 monitor addresses */
1910
	if (($gateway_settings['monitor'] <> "") && is_ipaddr($gateway_settings['monitor']) && $gateway_settings['monitor'] != "dynamic") {
1911
		if (is_ipaddrv6($gateway_settings['monitor']) && ($gateway_settings['ipprotocol'] == "inet")) {
1912
			$input_errors[] = sprintf(gettext("The IPv6 monitor address '%s' can not be used on a IPv4 gateway."), $gateway_settings['monitor']);
1913
		}
1914
		if (is_ipaddrv4($gateway_settings['monitor']) && ($gateway_settings['ipprotocol'] == "inet6")) {
1915
			$input_errors[] = sprintf(gettext("The IPv4 monitor address '%s' can not be used on a IPv6 gateway."), $gateway_settings['monitor']);
1916
		}
1917
	}
1918

    
1919
	if (isset($gateway_settings['name'])) {
1920
		/* check for overlaps */
1921
		foreach ($a_gateways as $gateway) {
1922
			if (isset($id) && ($a_gateways[$id]) && ($a_gateways[$id] === $gateway)) {
1923
				if ($gateway['name'] != $gateway_settings['name']) {
1924
					$input_errors[] = gettext("Changing name on a gateway is not allowed.");
1925
				}
1926
				continue;
1927
			}
1928
			if ($gateway_settings['name'] <> "") {
1929
				if (($gateway['name'] <> "") && ($gateway_settings['name'] == $gateway['name']) && ($gateway['attribute'] !== "system")) {
1930
					$input_errors[] = sprintf(gettext('The gateway name "%s" already exists.'), $gateway_settings['name']);
1931
					break;
1932
				}
1933
			}
1934
			if (is_ipaddr($gateway_settings['gateway'])) {
1935
				if (($gateway['gateway'] <> "") && ($gateway_settings['gateway'] == $gateway['gateway']) && ($gateway['attribute'] !== "system")) {
1936
					$input_errors[] = sprintf(gettext('The gateway IP address "%s" already exists.'), $gateway_settings['gateway']);
1937
					break;
1938
				}
1939
			}
1940
			if (is_ipaddr($gateway_settings['monitor'])) {
1941
				if (($gateway['monitor'] <> "") && ($gateway_settings['monitor'] == $gateway['monitor']) && ($gateway['attribute'] !== "system")) {
1942
					$input_errors[] = sprintf(gettext('The monitor IP address "%s" is already in use. A different monitor IP must be chosen.'), $gateway_settings['monitor']);
1943
					break;
1944
				}
1945
			}
1946
		}
1947
	}
1948

    
1949
	/* input validation of dpinger advanced parameters */
1950

    
1951
	$dpinger_default = return_dpinger_defaults();
1952
	$latencylow = $dpinger_default['latencylow'];
1953
	if ($gateway_settings['latencylow']) {
1954
		if (!is_numeric($gateway_settings['latencylow'])) {
1955
			$input_errors[] = gettext("The low latency threshold needs to be a numeric value.");
1956
		} else if ($gateway_settings['latencylow'] < 1) {
1957
			$input_errors[] = gettext("The low latency threshold needs to be positive.");
1958
		} else {
1959
			$latencylow = $gateway_settings['latencylow'];
1960
		}
1961
	}
1962

    
1963
	$latencyhigh = $dpinger_default['latencyhigh'];
1964
	if ($gateway_settings['latencyhigh']) {
1965
		if (!is_numeric($gateway_settings['latencyhigh'])) {
1966
			$input_errors[] = gettext("The high latency threshold needs to be a numeric value.");
1967
		} else if ($gateway_settings['latencyhigh'] < 1) {
1968
			$input_errors[] = gettext("The high latency threshold needs to be positive.");
1969
		} else {
1970
			$latencyhigh = $gateway_settings['latencyhigh'];
1971
		}
1972
	}
1973

    
1974
	$losslow = $dpinger_default['losslow'];
1975
	if ($gateway_settings['losslow']) {
1976
		if (!is_numeric($gateway_settings['losslow'])) {
1977
			$input_errors[] = gettext("The low Packet Loss threshold needs to be a numeric value.");
1978
		} else if ($gateway_settings['losslow'] < 1) {
1979
			$input_errors[] = gettext("The low Packet Loss threshold needs to be positive.");
1980
		} else if ($gateway_settings['losslow'] >= 100) {
1981
			$input_errors[] = gettext("The low Packet Loss threshold needs to be less than 100.");
1982
		} else {
1983
			$losslow = $gateway_settings['losslow'];
1984
		}
1985
	}
1986

    
1987
	$losshigh = $dpinger_default['losshigh'];
1988
	if ($gateway_settings['losshigh']) {
1989
		if (!is_numeric($gateway_settings['losshigh'])) {
1990
			$input_errors[] = gettext("The high Packet Loss threshold needs to be a numeric value.");
1991
		} else if ($gateway_settings['losshigh'] < 1) {
1992
			$input_errors[] = gettext("The high Packet Loss threshold needs to be positive.");
1993
		} else if ($gateway_settings['losshigh'] > 100) {
1994
			$input_errors[] = gettext("The high Packet Loss threshold needs to be 100 or less.");
1995
		} else {
1996
			$losshigh = $gateway_settings['losshigh'];
1997
		}
1998
	}
1999

    
2000
	$time_period = $dpinger_default['time_period'];
2001
	if ($gateway_settings['time_period']) {
2002
		if (!is_numeric($gateway_settings['time_period'])) {
2003
			$input_errors[] = gettext("The time period over which results are averaged needs to be a numeric value.");
2004
		} else if ($gateway_settings['time_period'] < 1) {
2005
			$input_errors[] = gettext("The time period over which results are averaged needs to be positive.");
2006
		} else {
2007
			$time_period = $gateway_settings['time_period'];
2008
		}
2009
	}
2010

    
2011
	$interval = $dpinger_default['interval'];
2012
	if ($gateway_settings['interval']) {
2013
		if (!is_numeric($gateway_settings['interval'])) {
2014
			$input_errors[] = gettext("The probe interval needs to be a numeric value.");
2015
		} else if ($gateway_settings['interval'] < 1) {
2016
			$input_errors[] = gettext("The probe interval needs to be positive.");
2017
		} else {
2018
			$interval = $gateway_settings['interval'];
2019
		}
2020
	}
2021

    
2022
	$loss_interval = $dpinger_default['loss_interval'];
2023
	if ($gateway_settings['loss_interval']) {
2024
		if (!is_numeric($gateway_settings['loss_interval'])) {
2025
			$input_errors[] = gettext("The loss interval needs to be a numeric value.");
2026
		} else if ($gateway_settings['loss_interval'] < 1) {
2027
			$input_errors[] = gettext("The loss interval setting needs to be positive.");
2028
		} else {
2029
			$loss_interval = $gateway_settings['loss_interval'];
2030
		}
2031
	}
2032

    
2033
	$alert_interval = $dpinger_default['alert_interval'];
2034
	if ($gateway_settings['alert_interval']) {
2035
		if (!is_numeric($gateway_settings['alert_interval'])) {
2036
			$input_errors[] = gettext("The alert interval needs to be a numeric value.");
2037
		} else if ($gateway_settings['alert_interval'] < 1) {
2038
			$input_errors[] = gettext("The alert interval setting needs to be positive.");
2039
		} else {
2040
			$alert_interval = $gateway_settings['alert_interval'];
2041
		}
2042
	}
2043

    
2044
	if ($latencylow >= $latencyhigh) {
2045
		$input_errors[] = gettext(
2046
		    "The high latency threshold needs to be greater than the low latency threshold");
2047
	}
2048

    
2049
	if ($losslow >= $losshigh) {
2050
		$input_errors[] = gettext(
2051
		    "The high packet loss threshold needs to be higher than the low packet loss threshold");
2052
	}
2053

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

    
2060
	// Ensure that the time period is greater than 2 times the probe interval plus the loss interval.
2061
	if (($interval * 2 + $loss_interval) >= $time_period) {
2062
		$input_errors[] = gettext("The time period needs to be greater than twice the probe interval plus the loss interval.");
2063
	}
2064

    
2065
	// There is no point recalculating the average latency and loss more often than the probe interval.
2066
	// So the alert interval needs to be >= probe interval.
2067
	if ($interval > $alert_interval) {
2068
		$input_errors[] = gettext("The alert interval needs to be greater than or equal to the probe interval.");
2069
	}
2070

    
2071
	return $input_errors;
2072
}
2073

    
2074
// Save gateway settings.
2075
// $gateway_settings - the array of gateway setting parameters
2076
// $realid - the index of the gateway to be modified (otherwise "" if adding a new gateway)
2077

    
2078
// This function is responsible to:
2079
//   Setup the gateway parameter structure from the gateway settings input parameter
2080
//   Save the structure into the config
2081
//   Remove any run-time settings from gateway parameters that are changed (e.g. remove routes to addresses that are changing)
2082

    
2083
// A subsequent "apply" step will implement the added/changed gateway.
2084

    
2085
function save_gateway($gateway_settings, $realid = "") {
2086
	global $config;
2087

    
2088
	init_config_arr(array('gateways', 'gateway_item'));
2089
	$a_gateway_item = &$config['gateways']['gateway_item'];
2090
	$reloadif = "";
2091
	$gateway = array();
2092

    
2093
	if (empty($gateway_settings['interface'])) {
2094
		$gateway['interface'] = $gateway_settings['friendlyiface'];
2095
	} else {
2096
		$gateway['interface'] = $gateway_settings['interface'];
2097
	}
2098
	if (is_ipaddr($gateway_settings['gateway'])) {
2099
		$gateway['gateway'] = $gateway_settings['gateway'];
2100
	} else {
2101
		$gateway['gateway'] = "dynamic";
2102
	}
2103
	$gateway['name'] = $gateway_settings['name'];
2104
	$gateway['weight'] = $gateway_settings['weight'];
2105
	$gateway['ipprotocol'] = $gateway_settings['ipprotocol'];
2106
	if ($gateway_settings['interval']) {
2107
		$gateway['interval'] = $gateway_settings['interval'];
2108
	}
2109

    
2110
	if ($gateway_settings['time_period']) {
2111
		$gateway['time_period'] = $gateway_settings['time_period'];
2112
	}
2113
	if ($gateway_settings['alert_interval']) {
2114
		$gateway['alert_interval'] = $gateway_settings['alert_interval'];
2115
	}
2116

    
2117
	$gateway['descr'] = $gateway_settings['descr'];
2118
	if ($gateway_settings['monitor_disable'] == "yes") {
2119
		$gateway['monitor_disable'] = true;
2120
	}
2121
	if ($gateway_settings['action_disable'] == "yes") {
2122
		$gateway['action_disable'] = true;
2123
	}
2124
	if ($gateway_settings['nonlocalgateway'] == "yes") {
2125
		$gateway['nonlocalgateway'] = true;
2126
	}
2127
	if ($gateway_settings['dpinger_dont_add_static_route'] == "yes") {
2128
		$gateway['dpinger_dont_add_static_route'] = true;
2129
	}
2130
	if ($gateway_settings['force_down'] == "yes") {
2131
		$gateway['force_down'] = true;
2132
	}
2133
	$gateway['gw_down_kill_states'] = $gateway_settings['gw_down_kill_states'];
2134
	if (is_ipaddr($gateway_settings['monitor'])) {
2135
		$gateway['monitor'] = $gateway_settings['monitor'];
2136
	}
2137
	if (isset($gateway_settings['data_payload']) && is_numeric($gateway_settings['data_payload']) && $gateway_settings['data_payload'] >= 0) {
2138
		$gateway['data_payload'] = $gateway_settings['data_payload'];
2139
	}
2140

    
2141
	/* NOTE: If gateway ip is changed need to cleanup the old static interface route */
2142
	if ($gateway_settings['monitor'] != "dynamic" &&
2143
	    !empty($a_gateway_item[$realid]) &&
2144
	    is_ipaddr($a_gateway_item[$realid]['gateway']) &&
2145
	    $gateway['gateway'] != $a_gateway_item[$realid]['gateway'] &&
2146
	    isset($a_gateway_item[$realid]["nonlocalgateway"])) {
2147
		route_del($a_gateway_item[$realid]['gateway']);
2148
	}
2149

    
2150
	/* NOTE: If monitor ip is changed need to cleanup the old static route */
2151
	if ($gateway_settings['monitor'] != "dynamic" &&
2152
	    !empty($a_gateway_item[$realid]) &&
2153
	    is_ipaddr($a_gateway_item[$realid]['monitor']) &&
2154
	    $gateway_settings['monitor'] != $a_gateway_item[$realid]['monitor'] &&
2155
	    $gateway['gateway'] != $a_gateway_item[$realid]['monitor']) {
2156
		route_del($a_gateway_item[$realid]['monitor']);
2157
	}
2158

    
2159
	if ($gateway_settings['defaultgw'] == "yes" || $gateway_settings['defaultgw'] == "on") {
2160
		// a new default gateway is being saved.
2161
		$i = 0;
2162
		/* remove the default gateway bits for all gateways with the same address family */
2163
		if (is_array($a_gateway_item)) {
2164
			foreach ($a_gateway_item as $gw) {
2165
				if ($gateway['ipprotocol'] == $gw['ipprotocol']) {
2166
					if ($gw['interface'] != $gateway_settings['interface'] &&
2167
						($gw['name'] == $config['gateways']['defaultgw4'] || $gw['name'] == $config['gateways']['defaultgw6'])) {
2168
						// remember the old default gateway interface to call with a "interface reconfigure" event.
2169
						$reloadif = $gw['interface'];
2170
					}
2171
				}
2172
				$i++;
2173
			}
2174
		}
2175
		if ($gateway['ipprotocol'] == "inet") {
2176
			$config['gateways']['defaultgw4'] = $gateway['name'];
2177
		} elseif ($gateway['ipprotocol'] == "inet6") {
2178
			$config['gateways']['defaultgw6'] = $gateway['name'];
2179
		}
2180
	}
2181

    
2182
	if ($gateway_settings['latencylow']) {
2183
		$gateway['latencylow'] = $gateway_settings['latencylow'];
2184
	}
2185
	if ($gateway_settings['latencyhigh']) {
2186
		$gateway['latencyhigh'] = $gateway_settings['latencyhigh'];
2187
	}
2188
	if ($gateway_settings['losslow']) {
2189
		$gateway['losslow'] = $gateway_settings['losslow'];
2190
	}
2191
	if ($gateway_settings['losshigh']) {
2192
		$gateway['losshigh'] = $gateway_settings['losshigh'];
2193
	}
2194
	if ($gateway_settings['loss_interval']) {
2195
		$gateway['loss_interval'] = $gateway_settings['loss_interval'];
2196
	}
2197

    
2198
	/* reload IPsec and OpenVPN on gateway IP, 'Mark Gateway as Down', or 'Disabled' option change
2199
	 * see https://redmine.pfsense.org/issues/13076 */
2200
	if (!empty($a_gateway_item[$realid]) &&
2201
	    (isset($gateway['disabled']) ^ isset($a_gateway_item[$realid]['disabled'])) ||
2202
	    (!isset($a_gateway_item[$realid]['disabled']) &&
2203
	    ((($gateway['monitor'] != "dynamic") &&
2204
	    is_ipaddr($a_gateway_item[$realid]['gateway']) &&
2205
	    ($gateway['gateway'] != $a_gateway_item[$realid]['gateway'])) ||
2206
	    (isset($gateway['force_down']) ^ isset($a_gateway_item[$realid]['force_down']))))) {
2207
		$reloadvpn = true;
2208
	}
2209

    
2210
	/* when saving the manual gateway we use the attribute which has the corresponding id */
2211
	if (isset($realid) && $a_gateway_item[$realid]) {
2212
		$preserve_disabled = isset($a_gateway_item[$realid]['disabled']);
2213
		$a_gateway_item[$realid] = $gateway;
2214
		if ($preserve_disabled) {
2215
			$a_gateway_item[$realid]['disabled'] = true;
2216
		}
2217
	} else {
2218
		$a_gateway_item[] = $gateway;
2219
	}
2220
	gateway_set_enabled($gateway_settings['name'], !isset($gateway_settings['disabled']));
2221

    
2222
	mark_subsystem_dirty('staticroutes');
2223

    
2224
	write_config("Gateway settings changed");
2225

    
2226
	if ($reloadvpn) {
2227
		send_event("service reload ipsec " . escapeshellarg($gateway['name']));
2228
		send_event("service reload openvpn " . escapeshellarg($gateway['name']));
2229
	}
2230

    
2231
	if (!empty($reloadif)) {
2232
		send_event("interface reconfigure {$reloadif}");
2233
	}
2234
}
2235

    
2236
function gateway_set_enabled($name, $enabled) {
2237
	global $config;
2238
	if (is_array($config['gateways']['gateway_item'])) {
2239
		foreach($config['gateways']['gateway_item'] as &$item) {
2240
			if ($item['name'] == $name) {
2241
				$gateway = &$item;
2242
			}
2243
		}
2244
	}
2245
	if (!isset($gateway)) {
2246
		return;
2247
	}
2248
	if ($enabled) {
2249
		unset($gateway['disabled']);
2250
	} else {
2251
		/* Check if the gateway was enabled but changed to disabled. */
2252
		if (!isset($gateway['disabled'])) {
2253
			/*  If the disabled gateway was the default route, remove the default route */
2254
			if (is_ipaddr($gateway['gateway'])) {
2255
				$inet = (!is_ipaddrv4($gateway['gateway']) ? 'inet6' : 'inet');
2256
				if ($inet == 'inet') {
2257
					$cgw = route_get_default('inet');
2258
				} else {
2259
					$cgw = route_get_default('inet6');
2260
				}
2261
				if ($gateway['gateway'] == $cgw) {
2262
					route_del("default", $inet);
2263
				}
2264
			}
2265
			$gateway['disabled'] = true;
2266
		}
2267
	}
2268
}
2269

    
2270
function gateway_or_gwgroup_exists($name) {
2271
	global $config;
2272
	if (is_array($config['gateways']['gateway_item'])) {
2273
		foreach($config['gateways']['gateway_item'] as $item) {
2274
			if ($item['name'] == $name) {
2275
				return true;
2276
			}
2277
		}
2278
	}
2279
	if (is_array($config['gateways']['gateway_group'])) {
2280
		foreach($config['gateways']['gateway_group'] as $item) {
2281
			if ($item['name'] == $name) {
2282
				return true;
2283
			}
2284
		}
2285
	}
2286
	return false;
2287
}
2288

    
2289
// These two replacement functions avoid the need to call return_gateways_array() multiple times and
2290
// allow system_gateways.php to get everything it needs in a single function call
2291
function gateway_getgwtiername($gways, $idx) {
2292
	global $config;
2293

    
2294
	$result = "";
2295
	$gwname = $gways[$idx]['name'];
2296

    
2297
	$gw = get_gateway_or_group_by_name($gwname, $gways);
2298
	init_config_arr(array('gateways'));
2299
	if ($config['gateways']['defaultgw4'] == $gwname || $config['gateways']['defaultgw6'] == $gwname) {
2300
		$result = "Default";
2301
	} else {
2302
		if ($gw['ipprotocol'] == 'inet') {
2303
			$defgw = get_gateway_or_group_by_name($config['gateways']['defaultgw4'], $gways);
2304
		} else {
2305
			$defgw = get_gateway_or_group_by_name($config['gateways']['defaultgw6'], $gways);
2306
		}
2307

    
2308
		if ($defgw['type'] == "gatewaygroup") {
2309
			$detail = gateway_is_gwgroup_member($gwname, true);
2310
			foreach($detail as $gwitem) {
2311
				if ($gwitem['name'] == $defgw['name']) {
2312
					if (isset($gwitem['tier'])) {
2313
						$result = "Tier " . $gwitem['tier'];
2314
						break;
2315
					}
2316
				}
2317
			}
2318
		}
2319
    }
2320

    
2321
	if (!empty($result)) {
2322
		if ($gw['ipprotocol'] == "inet") {
2323
			$result .= " (IPv4)";
2324
		} elseif ($gw['ipprotocol'] == "inet6") {
2325
			$result .= " (IPv6)";
2326
		}
2327
	}
2328

    
2329
	return $result;
2330
}
2331

    
2332
function get_gateway_or_group_by_name($gwname, $gateways_arr) {
2333
	global $config;
2334

    
2335
	foreach ($gateways_arr as $gw) {
2336
		if ($gw['name'] == $gwname) {
2337
			$gw['type'] = 'gateway';
2338
			return $gw;
2339
		}
2340
	}
2341

    
2342
	init_config_arr(array('gateways', 'gateway_group'));
2343
	foreach ($config['gateways']['gateway_group'] as $gwg) {
2344
		if ($gwg['name'] == $gwname) {
2345
			$gwg['type'] = 'gatewaygroup';
2346
			return $gwg;
2347
		}
2348
	}
2349

    
2350
	return false;
2351
}
2352

    
2353
// Compose a list of available gateways but without the need to call return_gateways_array() multiple times
2354
// Previously that function could be called eight times per gateway!
2355
function available_default_gateways() {
2356
	global $config;
2357

    
2358
	$gways = return_gateways_array(true, false, true, true);
2359

    
2360
	$items4 = array();
2361
	$items6 = array();
2362
	$items4[''] = "Automatic";
2363
	$items6[''] = "Automatic";
2364
	foreach($gways as $gw) {
2365
		$gwn = $gw['name'];
2366
		if ($gw['ipprotocol'] == "inet6") {
2367
			$items6[$gwn] = $gwn;
2368
		} else {
2369
			$items4[$gwn] = $gwn;
2370
		}
2371
	}
2372

    
2373
	$groups = return_gateway_groups_array(false, $gways);
2374
	foreach ($groups as $key => $group) {
2375
		$gwn = $group['descr'];
2376
		if ($group['ipprotocol'] == "inet6") {
2377
			$items6[$key] = "$key ($gwn)";
2378
		} else {
2379
			$items4[$key] = "$key ($gwn)";
2380
		}
2381
	}
2382
	$items4['-'] = "None";
2383
	$items6['-'] = "None";
2384

    
2385
	$defaults = array();
2386
	$defaults['v4'] = $items4;
2387
	$defaults['v6'] = $items6;
2388
	$defaults['defaultgw4'] = $config['gateways']['defaultgw4'];
2389
	$defaults['defaultgw6'] = $config['gateways']['defaultgw6'];
2390

    
2391
	return $defaults;
2392
}
2393

    
2394

    
2395
?>
(21-21/61)