Project

General

Profile

Download (76.8 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_get_path('gateways/defaultgw4', "");
1127
	} else {
1128
		$gwdefault = config_get_path('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) &&
1184
				    is_array($gwgroupitem) &&
1185
				    ($gwgroupitem['gwip'] == $currentdefaultgwip)) {
1186
					$set_dfltgwname = $gwgroupitem['gw'];
1187
					$found_current = true;
1188
					if (isset($config['system']['gw-debug'])) {
1189
						log_error("Keep current gateway, its already part of the group members.");
1190
					}
1191
					break;
1192
				}
1193
			}
1194
			if (!$found_current) {
1195
				$set_dfltgwname = $gwg_members[0]['gw'];
1196
				log_error(sprintf("Gateway, switch to: %s", $set_dfltgwname));
1197
			}
1198
		} else {
1199
			log_error("Gateway, NONE AVAILABLE");
1200
		}
1201
	}
1202
	if (!empty($set_dfltgwname) && isset($gateways_arr[$set_dfltgwname])) {
1203
		setdefaultgateway($gateways_arr[$set_dfltgwname]);
1204
	} elseif (empty($set_dfltgwname)) {
1205
		route_del('default', $ipprotocol); 
1206
	}
1207
}
1208

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1449
	return ($gateway_groups_array);
1450
}
1451

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

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

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

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

    
1477
function lookup_gateway_or_group_by_name($gwname, $gways = false) {
1478
	global $config;
1479

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

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

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

    
1501
	return false;
1502
}
1503

    
1504
function lookup_gateway_ip_by_name($name, $disabled = false) {
1505

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

    
1513
	return false;
1514
}
1515

    
1516
function lookup_gateway_monitor_ip_by_name($name) {
1517

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

    
1525
		return $gateway['monitor'];
1526
	}
1527

    
1528
	return (false);
1529
}
1530

    
1531
function lookup_gateway_interface_by_name($name) {
1532

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

    
1539
	return (false);
1540
}
1541

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

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

    
1555
	$interface = get_root_interface($interface);
1556

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

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

    
1579
	}
1580

    
1581
	/* return gateway */
1582
	return ($gw);
1583
}
1584

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

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

    
1599
	$interface = get_root_interface($interface);
1600

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

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

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

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

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

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

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

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

    
1682
	return false;
1683
}
1684

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

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

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

    
1711
	return false;
1712
}
1713

    
1714
function gateway_is_gwgroup_member($name, $detail=false) {
1715
	global $config;
1716

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

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

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

    
1759
	$a_gateways = return_gateways_array(true, false, true, true);
1760
	$input_errors = array();
1761

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

    
1766
	do_input_validation($gateway_settings, $reqdfields, $reqdfieldsn, $input_errors);
1767

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

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

    
1799
		// Check if the gateway name is used by any DNS Server
1800
		$dnsgw_counter = 1;
1801
		while (isset($config["system"]["dns{$dnsgw_counter}gw"])) {
1802
			if ($gateway_settings['name'] == $config["system"]["dns{$dnsgw_counter}gw"]) {
1803
				// The user wants to disable this gateway, but there is a static route to the DNS server that refers to the gateway.
1804
				$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"]);
1805
			}
1806
			$dnsgw_counter++;
1807
		}
1808
	}
1809
	/* skip system gateways which have been automatically added */
1810
	if (($gateway_settings['gateway'] && (!is_ipaddr($gateway_settings['gateway'])) && ($gateway_settings['attribute'] !== "system")) && ($gateway_settings['gateway'] != "dynamic")) {
1811
		$input_errors[] = gettext("A valid gateway IP address must be specified.");
1812
	}
1813

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

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

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

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

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

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

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

    
1951
	/* input validation of dpinger advanced parameters */
1952

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2073
	return $input_errors;
2074
}
2075

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

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

    
2085
// A subsequent "apply" step will implement the added/changed gateway.
2086

    
2087
function save_gateway($gateway_settings, $realid = "") {
2088
	global $config;
2089

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

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

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

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

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

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

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

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

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

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

    
2225
	mark_subsystem_dirty('staticroutes');
2226

    
2227
	write_config("Gateway settings changed");
2228

    
2229
	if ($reloadvpn) {
2230
		send_event("service reload ipsec " . escapeshellarg($gateway['name']));
2231
		send_event("service reload openvpn " . escapeshellarg($gateway['name']));
2232
	}
2233

    
2234
	if (!empty($reloadif)) {
2235
		send_event("interface reconfigure {$reloadif}");
2236
	}
2237
}
2238

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

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

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

    
2297
	$result = "";
2298
	$gwname = $gways[$idx]['name'];
2299

    
2300
	$gw = get_gateway_or_group_by_name($gwname, $gways);
2301
	
2302
	init_config_arr(array('gateways'));
2303
	$gw4 = config_get_path('gateways/defaultgw4', "");
2304
	$gw6 = config_get_path('gateways/defaultgw6', "");
2305
	if ($gw4 == $gwname || $gw6 == $gwname) {
2306
		$result = "Default";
2307
	} else {
2308
		if ($gw['ipprotocol'] == 'inet') {
2309
			$defgw = get_gateway_or_group_by_name($gw4, $gways);
2310
		} else {
2311
			$defgw = get_gateway_or_group_by_name($gw6, $gways);
2312
		}
2313

    
2314
		if ($defgw['type'] == "gatewaygroup") {
2315
			$detail = gateway_is_gwgroup_member($gwname, true);
2316
			foreach($detail as $gwitem) {
2317
				if ($gwitem['name'] == $defgw['name']) {
2318
					if (isset($gwitem['tier'])) {
2319
						$result = "Tier " . $gwitem['tier'];
2320
						break;
2321
					}
2322
				}
2323
			}
2324
		}
2325
    }
2326

    
2327
	if (!empty($result)) {
2328
		if ($gw['ipprotocol'] == "inet") {
2329
			$result .= " (IPv4)";
2330
		} elseif ($gw['ipprotocol'] == "inet6") {
2331
			$result .= " (IPv6)";
2332
		}
2333
	}
2334

    
2335
	return $result;
2336
}
2337

    
2338
function get_gateway_or_group_by_name($gwname, $gateways_arr) {
2339
	global $config;
2340

    
2341
	foreach ($gateways_arr as $gw) {
2342
		if ($gw['name'] == $gwname) {
2343
			$gw['type'] = 'gateway';
2344
			return $gw;
2345
		}
2346
	}
2347

    
2348
	init_config_arr(array('gateways', 'gateway_group'));
2349
	foreach ($config['gateways']['gateway_group'] as $gwg) {
2350
		if ($gwg['name'] == $gwname) {
2351
			$gwg['type'] = 'gatewaygroup';
2352
			return $gwg;
2353
		}
2354
	}
2355

    
2356
	return false;
2357
}
2358

    
2359
// Compose a list of available gateways but without the need to call return_gateways_array() multiple times
2360
// Previously that function could be called eight times per gateway!
2361
function available_default_gateways() {
2362
	global $config;
2363

    
2364
	$gways = return_gateways_array(true, false, true, true);
2365

    
2366
	$items4 = array();
2367
	$items6 = array();
2368
	$items4[''] = "Automatic";
2369
	$items6[''] = "Automatic";
2370
	foreach($gways as $gw) {
2371
		$gwn = $gw['name'];
2372
		if ($gw['ipprotocol'] == "inet6") {
2373
			$items6[$gwn] = $gwn;
2374
		} else {
2375
			$items4[$gwn] = $gwn;
2376
		}
2377
	}
2378

    
2379
	$groups = return_gateway_groups_array(false, $gways);
2380
	foreach ($groups as $key => $group) {
2381
		$gwn = $group['descr'];
2382
		if ($group['ipprotocol'] == "inet6") {
2383
			$items6[$key] = "$key ($gwn)";
2384
		} else {
2385
			$items4[$key] = "$key ($gwn)";
2386
		}
2387
	}
2388
	$items4['-'] = "None";
2389
	$items6['-'] = "None";
2390

    
2391
	$defaults = array();
2392
	$defaults['v4'] = $items4;
2393
	$defaults['v6'] = $items6;
2394
	$defaults['defaultgw4'] = config_get_path('gateways/defaultgw4', "");
2395
	$defaults['defaultgw6'] = config_get_path('gateways/defaultgw6', "");
2396

    
2397
	return $defaults;
2398
}
2399

    
2400

    
2401
?>
(22-22/62)