Project

General

Profile

Download (70.1 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * gwlb.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2008 Bill Marquette, Seth Mos
7
 * Copyright (c) 2008-2018 Rubicon Communications, LLC (Netgate)
8
 * All rights reserved.
9
 *
10
 * Licensed under the Apache License, Version 2.0 (the "License");
11
 * you may not use this file except in compliance with the License.
12
 * You may obtain a copy of the License at
13
 *
14
 * http://www.apache.org/licenses/LICENSE-2.0
15
 *
16
 * Unless required by applicable law or agreed to in writing, software
17
 * distributed under the License is distributed on an "AS IS" BASIS,
18
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
 * See the License for the specific language governing permissions and
20
 * limitations under the License.
21
 */
22

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

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

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

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

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

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

    
66
	return $result;
67
}
68

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

    
77
	$running_processes = running_dpinger_processes();
78

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

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

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

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

    
99
	$dpinger_defaults = return_dpinger_defaults();
100

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
246
				pfSense_kill_states("0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmp");
247
			}
248
		} else if ($gateway['ipprotocol'] == "inet6") { // This is an IPv6 gateway...
249
			if (is_linklocal($gateway['gateway']) &&
250
			    get_ll_scope($gateway['gateway']) == '') {
251
				$gateway['gateway'] .= '%' . $gateway['interface'];
252
			}
253

    
254
			if (is_linklocal($gateway['monitor'])) {
255
				if (get_ll_scope($gateway['monitor']) == '') {
256
					$gateways_arr[$gwname]['monitor'] .= '%' . $gateway['interface'];
257
				}
258

    
259
				$gwifip = find_interface_ipv6_ll($gateway['interface'], true);
260

    
261
				if (get_ll_scope($gwifip) == '') {
262
					$gwifip .= '%' . $gateway['interface'];
263
				}
264
			} else {
265
				$gwifip = find_interface_ipv6($gateway['interface'], true);
266
			}
267

    
268
			if (!is_ipaddrv6($gwifip)) {
269
				continue; //Skip this target
270
			}
271

    
272
			/*
273
			 * If the gateway is the same as the monitor we do not add a
274
			 * route as this will break the routing table.
275
			 * Add static routes for each gateway with their monitor IP
276
			 * not strictly necessary but is a added level of protection.
277
			 */
278
			if ($gateway['gateway'] != $gateway['monitor']) {
279
				log_error(sprintf(gettext('Removing static route for monitor %1$s and adding a new route through %2$s'), $gateway['monitor'], $gateway['gateway']));
280
				$route_to = "-host -inet6 {$gateway['monitor']}";
281
				if (interface_isppp_type($gateway['friendlyiface'])) {
282
					route_add_or_change("{$route_to} -iface {$gateway['interface']}");
283
				} else {
284
					route_add_or_change("{$route_to} {$gateway['gateway']}");
285
				}
286

    
287
				pfSense_kill_states("::0.0.0.0/0", $gateway['monitor'], $gateway['interface'], "icmpv6");
288
			}
289
		} else {
290
			continue;
291
		}
292

    
293
		$monitor_ips[] = $gateway['monitor'];
294
		$gateways_arr[$gwname]['enable_dpinger'] = true;
295
		$gateways_arr[$gwname]['gwifip'] = $gwifip;
296
	}
297

    
298
	stop_dpinger();
299

    
300
	/* Start new processes */
301
	foreach ($gateways_arr as $gateway) {
302
		if (!isset($gateway['enable_dpinger'])) {
303
			continue;
304
		}
305

    
306
		if (start_dpinger($gateway) != 0) {
307
			log_error(sprintf(gettext("Error starting gateway monitor for %s"), $gateway['name']));
308
		}
309
	}
310

    
311
	return;
312
}
313

    
314
function get_dpinger_status($gwname, $detailed = false) {
315
	global $g;
316

    
317
	$running_processes = running_dpinger_processes();
318

    
319
	if (!isset($running_processes[$gwname])) {
320
		log_error(sprintf(gettext('dpinger: No dpinger session running for gateway %s'), $gwname));
321
		return false;
322
	}
323

    
324
	$proc = $running_processes[$gwname];
325
	unset($running_processes);
326

    
327
	$timeoutcounter = 0;
328
	while (true) {
329
		if (!file_exists($proc['socket'])) {
330
			log_error("dpinger: status socket {$proc['socket']} not found");
331
			return false;
332
		}
333
		$fp = @stream_socket_client("unix://{$proc['socket']}", $errno, $errstr, 10);
334
		if (!$fp) {
335
			log_error(sprintf(gettext('dpinger: cannot connect to status socket %1$s - %2$s (%3$s)'), $proc['socket'], $errstr, $errno));
336
			return false;
337
		}
338

    
339
		$status = '';
340
		while (!feof($fp)) {
341
			$status .= fgets($fp, 1024);
342
		}
343
		fclose($fp);
344

    
345
		$r = array();
346
		list(
347
			$r['gwname'],
348
			$r['latency_avg'],
349
			$r['latency_stddev'],
350
			$r['loss']
351
		) = explode(' ', preg_replace('/\n/', '', $status));
352

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

    
358
		if ($ready) {
359
			break;
360
		} else {
361
			$timeoutcounter++;
362
			if ($timeoutcounter > 300) {
363
				log_error(sprintf(gettext('dpinger: timeout while retrieving status for gateway %s'), $gwname));
364
				return false;
365
			}
366
			usleep(10000);
367
		}
368
	}
369

    
370
	$r['srcip'] = $proc['srcip'];
371
	$r['targetip'] = $proc['targetip'];
372

    
373
	$gateways_arr = return_gateways_array();
374
	unset($gw);
375
	if (isset($gateways_arr[$gwname])) {
376
		$gw = $gateways_arr[$gwname];
377
	}
378

    
379
	$r['latency_avg'] = round($r['latency_avg']/1000, 3);
380
	$r['latency_stddev'] = round($r['latency_stddev']/1000, 3);
381

    
382
	$r['status'] = "none";
383
	if (isset($gw) && isset($gw['force_down'])) {
384
		$r['status'] = "force_down";
385
	} else if (isset($gw)) {
386
		$settings = return_dpinger_defaults();
387

    
388
		$keys = array(
389
		    'latencylow',
390
		    'latencyhigh',
391
		    'losslow',
392
		    'losshigh'
393
		);
394

    
395
		/* Replace default values by user-defined */
396
		foreach ($keys as $key) {
397
			if (isset($gw[$key]) && is_numeric($gw[$key])) {
398
				$settings[$key] = $gw[$key];
399
			}
400
		}
401

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

    
421
	return $r;
422
}
423

    
424
/* return the status of the dpinger targets as an array */
425
function return_gateways_status($byname = false) {
426
	global $config, $g;
427

    
428
	$dpinger_gws = running_dpinger_processes();
429
	$status = array();
430

    
431
	$gateways_arr = return_gateways_array();
432

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

    
443
		if ($byname == false) {
444
			$target = $dpinger_status['targetip'];
445
		} else {
446
			$target = $gwname;
447
		}
448

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

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

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

    
499
		$status[$target]['monitor_disable'] = true;
500
	}
501
	return($status);
502
}
503

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

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

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

    
544
	return $output;
545
}
546

    
547
function compare_gateway_order_configured($a, $b) {
548
	/* XXX WAN always has precedence */
549
	if ($a['friendlyiface'] == "wan") {
550
		return -1;
551
	} elseif ($b['friendlyiface'] == "wan") {
552
		return 1;
553
	}
554

    
555
	if ($a['attribute'] === $b['attribute']) {
556
		if ($a['attribute'] === 'system') {
557
			$res = (($a['name'] < $b['name'])) ? -1 : 1;
558
			return $res;
559
		}
560
		return 0;
561
	}
562
	if ($a['attribute'] === 'system' || $b['attribute'] === 'system') {
563
		$res = (($b['attribute'] === 'system')) ? -1 : 1;
564
		return $res;
565
	}
566
	$res = ($a['attribute'] < $b['attribute']) ? -1 : 1;
567
	return $res;
568
}
569

    
570
function order_gateways_as_configured($gateways_arr) {
571
	uasort($gateways_arr, 'compare_gateway_order_configured');
572
	return $gateways_arr;
573
}
574

    
575
/* Return all configured gateways on the system
576
   $disabled = true - include gateways that are disabled
577
   $localhost = true - include "Null" entries for localhost IP addresses
578
   $inactive = true - include gateways on inactive interfaces
579
   $integer_index = true - index the returned array by integers 0,1,2,... instead of by GW name
580
*/
581
function return_gateways_array($disabled = false, $localhost = false, $inactive = false, $integer_index = false) {
582
	global $config, $g;
583

    
584
	$gateways_arr = array();
585
	$gateways_arr_temp = array();
586
	$cgw4 = getcurrentdefaultgatewayip('inet');
587
	$cgw6 = getcurrentdefaultgatewayip('inet6');
588
	$found_defaultv4 = 0;
589
	$found_defaultv6 = 0;
590

    
591
	// Ensure the interface cache is up to date first
592
	$interfaces = get_interface_arr(true);
593

    
594
	$i = -1;
595
	/* Process/add all the configured gateways. */
596
	if (is_array($config['gateways']) && is_array($config['gateways']['gateway_item'])) {
597
		foreach ($config['gateways']['gateway_item'] as $gateway) {
598
			if (!is_array($gateway) || empty($gateway)) {
599
				continue;
600
			}
601
			
602
			/* Increment it here to do not skip items */
603
			$i++;
604
			if (isset($gateway['defaultgw'])) {
605
				unset($gateway['defaultgw']);
606
			}
607

    
608
			if (empty($config['interfaces'][$gateway['interface']])) {
609
				if ($inactive === false) {
610
					continue;
611
				} else {
612
					$gateway['inactive'] = true;
613
				}
614
			}
615
			$wancfg = $config['interfaces'][$gateway['interface']];
616

    
617
			/* skip disabled interfaces */
618
			if ($disabled === false && (!isset($wancfg['enable']))) {
619
				continue;
620
			}
621

    
622
			/* if the gateway is dynamic and we can find the IPv4, Great! */
623
			if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") {
624
				if ($gateway['ipprotocol'] == "inet") {
625
					/* we know which interfaces is dynamic, this should be made a function */
626
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
627
					/* no IP address found, set to dynamic */
628
					if (!is_ipaddrv4($gateway['gateway'])) {
629
						$gateway['gateway'] = "dynamic";
630
					}
631
					$gateway['dynamic'] = true;
632
				}
633

    
634
				/* if the gateway is dynamic and we can find the IPv6, Great! */
635
				else if ($gateway['ipprotocol'] == "inet6") {
636
					/* we know which interfaces is dynamic, this should be made a function, and for v6 too */
637
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
638
					/* no IPv6 address found, set to dynamic */
639
					if (!is_ipaddrv6($gateway['gateway'])) {
640
						$gateway['gateway'] = "dynamic";
641
					}
642
					$gateway['dynamic'] = true;
643
				}
644
			} else {
645
				/* getting this detection right is hard at this point because we still don't
646
				 * store the address family in the gateway item */
647
				if (is_ipaddrv4($gateway['gateway'])) {
648
					$gateway['ipprotocol'] = "inet";
649
				} else if (is_ipaddrv6($gateway['gateway'])) {
650
					$gateway['ipprotocol'] = "inet6";
651
				}
652
			}
653

    
654
			if (isset($gateway['monitor_disable'])) {
655
				$gateway['monitor_disable'] = true;
656
			} else if (empty($gateway['monitor'])) {
657
				$gateway['monitor'] = $gateway['gateway'];
658
			}
659

    
660
			if (isset($gateway['action_disable'])) {
661
				$gateway['action_disable'] = true;
662
			}
663

    
664
			$gateway['friendlyiface'] = $gateway['interface'];
665

    
666
			/* special treatment for tunnel interfaces */
667
			if ($gateway['ipprotocol'] == "inet6") {
668
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet6", false, false);
669
			} else {
670
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet", false, false);
671
			}
672

    
673
			if ($gateway['ipprotocol'] == "inet" &&
674
					($config['gateways']['defaultgw4'] == $gateway['name'] || $gateway['gateway'] == $cgw4)) {
675
				$gateway['isdefaultgw'] = true;
676
				$found_defaultv4 = 1;
677
			} else if ($gateway['ipprotocol'] == "inet6" &&
678
					($config['gateways']['defaultgw6'] == $gateway['name'] || $gateway['gateway'] == $cgw6)) {
679
				$gateway['isdefaultgw'] = true;
680
				$found_defaultv6 = 1;
681
			}
682
			/* include the gateway index as the attribute */
683
			$gateway['attribute'] = $i;
684

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

    
689
			/* skip disabled gateways if the caller has not asked for them to be returned. */
690
			if (!($disabled === false && isset($gateway['disabled']))) {
691
				$gateways_arr[$gateway['name']] = $gateway;
692
			}
693
		}
694
	}
695
	unset($gateway);
696

    
697
	//Sort the array by GW name before moving on.
698
	ksort($gateways_arr, SORT_STRING | SORT_FLAG_CASE);
699

    
700
	/* Loop through all interfaces with a gateway and add it to a array */
701
	if ($disabled == false) {
702
		$iflist = get_configured_interface_with_descr();
703
	} else {
704
		$iflist = get_configured_interface_with_descr(true);
705
	}
706

    
707
	/* Process/add dynamic v4 gateways. */
708
	foreach ($iflist as $ifname => $friendly) {
709
		if (!interface_has_gateway($ifname)) {
710
			continue;
711
		}
712

    
713
		if (empty($config['interfaces'][$ifname])) {
714
			continue;
715
		}
716

    
717
		$ifcfg = &$config['interfaces'][$ifname];
718
		if (!isset($ifcfg['enable'])) {
719
			continue;
720
		}
721

    
722
		if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) {
723
			continue;
724
		}
725

    
726
		$ctype = "";
727
		switch ($ifcfg['ipaddr']) {
728
			case "dhcp":
729
			case "pppoe":
730
			case "l2tp":
731
			case "pptp":
732
			case "ppp":
733
				$ctype = strtoupper($ifcfg['ipaddr']);
734
				break;
735
			default:
736
				$tunnelif = substr($ifcfg['if'], 0, 3);
737
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
738
					switch (substr($ifcfg['if'], 4, 1)) {
739
						case "c":
740
							$ovpntype = "openvpn-client";
741
							break;
742
						case "s":
743
							$ovpntype = "openvpn-server";
744
							break;
745
						default:
746
							// unknown ovpn type
747
							continue 2;
748
					}
749
					$ovpnid = substr($ifcfg['if'], 5);
750
					if (is_array($config['openvpn'][$ovpntype])) {
751
						foreach ($config['openvpn'][$ovpntype] as & $ovpnconf) {
752
							if ($ovpnconf['vpnid'] == $ovpnid) {
753
								// skip IPv6-only interfaces
754
								if ($ovpnconf['create_gw'] == "v6only") {
755
									continue 3;
756
								}
757
								// skip tap interfaces
758
								if ($ovpnconf['dev_mode'] == "tap") {
759
									continue 3;
760
								}
761
							}
762
						}
763
					}
764
					$ctype = "VPNv4";
765
				} elseif (substr($ifcfg['if'], 0, 5) == "ipsec") {
766
					$ikeid = substr($ifcfg['if'], 5);
767
					if (is_array($config['ipsec']) && is_array($config['ipsec']['phase1']) && is_array($config['ipsec']['phase2'])) {
768
						foreach ($config['ipsec']['phase1'] as $ph1ent) {
769
							if ($ph1ent['disabled']) {
770
								continue;
771
							}
772
							$vtisubnet_spec = ipsec_vti($ph1ent, true);
773
							// Skip non-VTI tunnels
774
							if (!$vtisubnet_spec || !is_array($vtisubnet_spec)) {
775
								continue;
776
							}
777
							if (!isset($ph1ent['mobile']) && ($keyexchange == 'ikev1' || isset($ph1ent['splitconn']))) {
778
								foreach ($vtisubnet_spec as $idx => $vtisub) {
779
									if ($ifcfg['if'] == "ipsec{$ph1ent['ikeid']}00{$idx}") {
780
										// If this specific VTI remote is v4, then we can make a v4 gw
781
										if (is_ipaddrv4($vtisub['right'])) {
782
											$ctype = "VTIv4";
783
										}
784
									}
785
								}
786
							} else {
787
								if ($ifcfg['if'] == "ipsec{$ph1ent['ikeid']}000") {
788
									// If any of the VTI remotes are v4, then we can make a v4 gw
789
									foreach ($vtisubnet_spec as $vtisub) {
790
										if (is_ipaddrv4($vtisub['right'])) {
791
											$ctype = "VTIv4";
792
										}
793
									}
794
								}
795
							}
796
						}
797
						if (empty($ctype)) {
798
							continue 2;
799
						}
800
					}
801
				} elseif ($tunnelif == "gif" || $tunnelif == "gre") {
802
					$ctype = "TUNNELv4";
803
				}
804
				break;
805
		}
806
		$ctype = "_". strtoupper($ctype);
807

    
808
		$gateway = array();
809
		$gateway['dynamic'] = false;
810
		$gateway['ipprotocol'] = "inet";
811
		$gateway['gateway'] = get_interface_gateway($ifname, $gateway['dynamic']);
812
		$gateway['interface'] = get_real_interface($ifname);
813
		$gateway['friendlyiface'] = $ifname;
814
		$gateway['name'] = "{$friendly}{$ctype}";
815
		$gateway['attribute'] = "system";
816

    
817
		if (($gateway['dynamic'] === "default") && ($found_defaultv4 == 0)) {
818
			$gateway['isdefaultgw'] = true;
819
			$gateway['dynamic'] = true;
820
			$found_defaultv4 = 1;
821
		}
822

    
823
		/* Loopback dummy for dynamic interfaces without a IP */
824
		if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) {
825
			$gateway['gateway'] = "dynamic";
826
		}
827

    
828
		/* automatically skip known static and dynamic gateways that were previously processed */
829
		foreach ($gateways_arr_temp as $gateway_item) {
830
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
831
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
832
				continue 2;
833
			}
834
		}
835

    
836
		if (is_ipaddrv4($gateway['gateway'])) {
837
			$gateway['monitor'] = $gateway['gateway'];
838
		}
839

    
840
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
841
		$gateways_arr[$gateway['name']] = $gateway;
842
	}
843
	unset($gateway);
844

    
845
	/* Process/add dynamic v6 gateways. */
846
	foreach ($iflist as $ifname => $friendly) {
847
		/* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */
848
		if (!isset($config['system']['ipv6allow'])) {
849
			break;
850
		}
851

    
852
		if (!interface_has_gatewayv6($ifname)) {
853
			continue;
854
		}
855

    
856
		if (empty($config['interfaces'][$ifname])) {
857
			continue;
858
		}
859

    
860
		$ifcfg = &$config['interfaces'][$ifname];
861
		if (!isset($ifcfg['enable'])) {
862
			continue;
863
		}
864

    
865
		if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) {
866
			continue;
867
		}
868

    
869
		$ctype = "";
870
		switch ($ifcfg['ipaddrv6']) {
871
			case "slaac":
872
			case "dhcp6":
873
			case "6to4":
874
			case "6rd":
875
				$ctype = strtoupper($ifcfg['ipaddrv6']);
876
				break;
877
			default:
878
				$tunnelif = substr($ifcfg['if'], 0, 3);
879
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
880
					switch (substr($ifcfg['if'], 4, 1)) {
881
						case "c":
882
							$ovpntype = "openvpn-client";
883
							break;
884
						case "s":
885
							$ovpntype = "openvpn-server";
886
							break;
887
						default:
888
							// unknown ovpn type
889
							continue 2;
890
					}
891
					$ovpnid = substr($ifcfg['if'], 5);
892
					if (is_array($config['openvpn'][$ovpntype])) {
893
						foreach ($config['openvpn'][$ovpntype] as & $ovpnconf) {
894
							if ($ovpnconf['vpnid'] == $ovpnid) {
895
								// skip IPv4-only interfaces
896
								if ($ovpnconf['create_gw'] == "v4only") {
897
									continue 3;
898
								}
899
								// skip tap interfaces
900
								if ($ovpnconf['dev_mode'] == "tap") {
901
									continue 3;
902
								}
903
							}
904
						}
905
					}
906
					$ctype = "VPNv6";
907
				} elseif (substr($ifcfg['if'], 0, 5) == "ipsec") {
908
					$ikeid = substr($ifcfg['if'], 5);
909
					if (is_array($config['ipsec']) && is_array($config['ipsec']['phase1']) && is_array($config['ipsec']['phase2'])) {
910
						foreach ($config['ipsec']['phase1'] as $ph1ent) {
911
							if ($ph1ent['disabled']) {
912
								continue;
913
							}
914
							$vtisubnet_spec = ipsec_vti($ph1ent, true);
915
							// Skip non-VTI tunnels
916
							if (!$vtisubnet_spec || !is_array($vtisubnet_spec)) {
917
								continue;
918
							}
919
							if (!isset($ph1ent['mobile']) && ($keyexchange == 'ikev1' || isset($ph1ent['splitconn']))) {
920
								foreach ($vtisubnet_spec as $idx => $vtisub) {
921
									if ($ifcfg['if'] == "ipsec{$ph1ent['ikeid']}00{$idx}") {
922
										// If this specific VTI remote is v6, then we can make a v6 gw
923
										if (is_ipaddrv6($vtisub['right'])) {
924
											$ctype = "VTIv6";
925
										}
926
									}
927
								}
928
							} else {
929
								if ($ifcfg['if'] == "ipsec{$ph1ent['ikeid']}000") {
930
									// If any of the VTI remotes are v6, then we can make a v6 gw
931
									foreach ($vtisubnet_spec as $vtisub) {
932
										if (is_ipaddrv6($vtisub['right'])) {
933
											$ctype = "VTIv6";
934
										}
935
									}
936
								}
937
							}
938
						}
939
						if (empty($ctype)) {
940
							continue 2;
941
						}
942
					}
943
				} else if ($tunnelif == "gif" || $tunnelif == "gre") {
944
					$ctype = "TUNNELv6";
945
				}
946
				break;
947
		}
948
		$ctype = "_". strtoupper($ctype);
949

    
950
		$gateway = array();
951
		$gateway['dynamic'] = false;
952
		$gateway['ipprotocol'] = "inet6";
953
		$gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']);
954
		$gateway['interface'] = get_real_interface($ifname, "inet6");
955
		switch ($ifcfg['ipaddrv6']) {
956
			case "6rd":
957
			case "6to4":
958
				$gateway['dynamic'] = "default";
959
				break;
960
		}
961
		$gateway['friendlyiface'] = $ifname;
962
		$gateway['name'] = "{$friendly}{$ctype}";
963
		$gateway['attribute'] = "system";
964

    
965
		if (($gateway['dynamic'] === "default") && ($found_defaultv6 == 0)) {
966
			$gateway['isdefaultgw'] = true;
967
			$gateway['dynamic'] = true;
968
			$found_defaultv6 = 1;
969
		}
970

    
971
		/* Loopback dummy for dynamic interfaces without a IP */
972
		if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) {
973
			$gateway['gateway'] = "dynamic";
974
		}
975

    
976
		/* automatically skip known static and dynamic gateways that were previously processed */
977
		foreach ($gateways_arr_temp as $gateway_item) {
978
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
979
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
980
				continue 2;
981
			}
982
		}
983

    
984
		if (is_ipaddrv6($gateway['gateway'])) {
985
			$gateway['monitor'] = $gateway['gateway'];
986
		}
987

    
988
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
989
		$gateways_arr[$gateway['name']] = $gateway;
990
	}
991
	unset($gateway);
992

    
993
	/* FIXME: Should this be enabled.
994
	 * Some interface like wan might be default but have no info recorded
995
	 * the config. */
996
	/* this is a fallback if all else fails and we want to get packets out @smos */
997
	if ($found_defaultv4 == 0 || $found_defaultv6 == 0) {
998
		foreach ($gateways_arr as &$gateway) {
999
			if (($gateway['friendlyiface'] == "wan") && ($found_defaultv4 == 0) && (!isset($gateway['ipprotocol']) || ($gateway['ipprotocol'] == "inet"))) {
1000
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgw")) {
1001
					$gateway['isdefaultgw'] = true;
1002
					$found_defaultv4 = 1;
1003
				}
1004
			}
1005
			else if (($gateway['friendlyiface'] == "wan") && ($found_defaultv6 == 0) && ($gateway['ipprotocol'] == "inet6")) {
1006
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgwv6")) {
1007
					$gateway['isdefaultgw'] = true;
1008
					$found_defaultv6 = 1;
1009
				}
1010
			}
1011
		}
1012
	}
1013

    
1014
	if ($localhost === true) {
1015
		/* attach localhost for Null routes */
1016
		$gwlo4 = array();
1017
		$gwlo4['name'] = "Null4";
1018
		$gwlo4['interface'] = "lo0";
1019
		$gwlo4['ipprotocol'] = "inet";
1020
		$gwlo4['gateway'] = "127.0.0.1";
1021
		$gwlo4['attribute'] = "system";
1022
		$gwlo6 = array();
1023
		$gwlo6['name'] = "Null6";
1024
		$gwlo6['interface'] = "lo0";
1025
		$gwlo6['ipprotocol'] = "inet6";
1026
		$gwlo6['gateway'] = "::1";
1027
		$gwlo6['attribute'] = "system";
1028
		$gateways_arr['Null4'] = $gwlo4;
1029
		$gateways_arr['Null6'] = $gwlo6;
1030
	}
1031

    
1032
	if ($integer_index) {
1033
		$gateways_arr = array_values($gateways_arr);
1034
	}
1035

    
1036
	if ($found_defaultv4 != 1 && is_ipaddr($cgw4)) {
1037
		foreach($gateways_arr as &$gw) {
1038
			if ($gw['gateway'] == $cgw4) {
1039
				$gw['isdefaultgw'] = true;
1040
			}
1041
		}
1042
	}
1043
	if ($found_defaultv6 != 1 && is_ipaddr($cgw6)) {
1044
		foreach($gateways_arr as &$gw) {
1045
			if ($gw['gateway'] == $cgw6) {
1046
				$gw['isdefaultgw'] = true;
1047
			}
1048
		}
1049
	}
1050
	return order_gateways_as_configured($gateways_arr);
1051
}
1052

    
1053
function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
1054
	global $config, $g;
1055
	/*
1056
	 * NOTE: The code below is meant to replace the default gateway when it goes down.
1057
	 *	This facilitates services running on pfSense itself and are not handled by a PBR to continue working.
1058
	 */
1059
	$set_dfltgwname = '';
1060

    
1061
	if ($ipprotocol == 'inet') {
1062
		$gwdefault = $config['gateways']['defaultgw4'];
1063
	} else {
1064
		$gwdefault = $config['gateways']['defaultgw6'];
1065
	}
1066
	if ($gwdefault == "-") {
1067
		// 'none', dont set the default gateway, useful if routes are managed by frr/bgp/ospf or similar
1068
		return;
1069
	}
1070
	if (isset($gateways_arr[$gwdefault])) {
1071
		// the configured gateway is a regular one. (not a gwgroup) use it as is..
1072
		$set_dfltgwname = $gwdefault;
1073
	} elseif (empty($gwdefault)) {
1074
		// 'automatic' mode, pick the first one thats 'up' or 'unmonitored' which is always considered up
1075
		$gateways_arr = order_gateways_as_configured($gateways_arr);
1076
		$fallback = "";
1077
		foreach($gateways_arr as $gwname => $gwsttng) {
1078
			if ($gwsttng['ipprotocol'] != $ipprotocol) {
1079
				continue;
1080
			}
1081
			
1082
			if ((isset($gwsttng['monitor_disable']) || isset($gwsttng['action_disable']) || $gateways_status[$gwname]['status'] == "none")) {
1083
				$set_dfltgwname = $gwname;
1084
				break;
1085
			}
1086
			if (empty($fallback) && $gwsttng['interface'] != 'lo0') {
1087
				$fallback = $gwname;
1088
			}
1089
		}
1090
		if (empty($set_dfltgwname)) {
1091
			log_error(sprintf("Gateway, none 'available' for %s, use the first one configured. '%s'", $ipprotocol, $fallback));
1092
			$set_dfltgwname = $fallback;
1093
		}
1094
	} else {
1095
		// a gwgroup is selected
1096
		// find the best available gateway given options available..
1097
		$gwg_members = array();
1098
		$viplist = get_configured_vip_list();
1099
		if (is_array($config['gateways']['gateway_group'])) {
1100
			foreach ($config['gateways']['gateway_group'] as $group) {
1101
				if ($group['name'] == $gwdefault) {
1102
					// finds the gw members of the best available tier for this group.
1103
					$gwg_members = get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1104
				}
1105
			}
1106
		}
1107

    
1108
		if (count($gwg_members) > 0) {
1109
			$currentdefaultgwip = getcurrentdefaultgatewayip($ipprotocol);
1110
			$found_current = false;
1111
			foreach($gwg_members as $gwgroupitem) {
1112
				if ($gwgroupitem['gwip'] == $currentdefaultgwip) {
1113
					$set_dfltgwname = $gwgroupitem['gw'];
1114
					$found_current = true;
1115
					if (isset($config['system']['gw-debug'])) {
1116
						log_error("Keep current gateway, its already part of the group members.");
1117
					}
1118
					break;
1119
				}
1120
			}
1121
			if (!$found_current) {
1122
				$set_dfltgwname = $gwg_members[0]['gw'];
1123
				log_error(sprintf("Gateway, switch to: %s", $set_dfltgwname));
1124
			}
1125
		} else {
1126
			log_error("Gateway, NONE AVAILABLE");
1127
		}
1128
	}
1129
	if (!empty($set_dfltgwname) && isset($gateways_arr[$set_dfltgwname])) {
1130
		setdefaultgateway($gateways_arr[$set_dfltgwname]);
1131
	}
1132
}
1133

    
1134
function getcurrentdefaultgatewayip($ipprotocol) {
1135
	return trim(exec("/sbin/route -n get -{$ipprotocol} default 2>/dev/null | /usr/bin/awk '/gateway:/ {print $2}'"), " \n");
1136
}
1137

    
1138
function setdefaultgateway($gw) {
1139
	global $g, $config;
1140
	if (isset($config['system']['route-debug'])) {
1141
		file_put_contents("/dev/console", "\n[".getmypid()."] SET DEF GW: {$gw['name']}");
1142
	}
1143
	$ipprotocol = $gw['ipprotocol'];
1144
	if ($gw['gateway'] == "dynamic") {
1145
		if ($ipprotocol == 'inet') {
1146
			$gw['gateway'] = get_interface_gateway($gw['friendlyiface']);
1147
		} else {
1148
			$gw['gateway'] = get_interface_gateway_v6($$gw['friendlyiface']);
1149
		}
1150
	}
1151
	if ($ipprotocol == 'inet6' && !is_ipaddrv6($gw['gateway'])) {
1152
		return;
1153
	}
1154
	if ($ipprotocol == 'inet' && !is_ipaddrv4($gw['gateway'])) {
1155
		return;
1156
	}
1157
	if ($ipprotocol == 'inet6') {
1158
		if (is_linklocal($gw['gateway']) && get_ll_scope($gw['gateway']) == '') {
1159
			$gw['gateway'] .= "%" . $gw['interface'];
1160
		}
1161
	}
1162
	$currentdefaultgwip = getcurrentdefaultgatewayip($ipprotocol);
1163
	if ($currentdefaultgwip != $gw['gateway']) {
1164
		log_error("Default gateway setting {$gw['descr']} as default.");
1165

    
1166
		if ($ipprotocol == 'inet') {
1167
			array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw", GLOB_BRACE));
1168
		} else {
1169
			array_map('unlink', glob("{$g['tmp_path']}/*_defaultgwv6", GLOB_BRACE));
1170
		}
1171
		$defaultif = get_real_interface($gw['interface']);
1172
		if ($defaultif) {
1173
			@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gw['gateway']);
1174
		}
1175

    
1176
		if (isset($gw["nonlocalgateway"])) {
1177
			if (is_ipaddr($gw['gateway']) && !empty($gw['interface'])) {
1178
				route_add_or_change("-{$ipprotocol} {$gw['gateway']} -iface {$gw['interface']}");
1179
			}
1180
		}
1181
		if (isset($config['system']['route-debug'])) {
1182
			file_put_contents("/dev/console", "\n[".getmypid()."] SET DEF GW: {$gw['name']} ({$gw['gateway']})");
1183
		}
1184
		route_add_or_change("-{$ipprotocol} default {$gw['gateway']}");
1185
		return true;
1186
	}
1187
}
1188

    
1189
function get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist){
1190
	$result = array();
1191
	/* create array with group gateways members separated by tier */
1192
	$tiers = array();
1193
	$backupplan = array();
1194
	$gwvip_arr = array();
1195
	foreach ($group['item'] as $item) {
1196
		list($gwname, $tier, $vipname) = explode("|", $item);
1197

    
1198
		if (is_ipaddr($viplist[$vipname])) {
1199
			if (!is_array($gwvip_arr[$group['name']])) {
1200
				$gwvip_arr[$group['name']] = array();
1201
			}
1202
			$gwvip_arr[$group['name']][$gwname] = $vipname;
1203
		}
1204

    
1205
		/* Do it here rather than reiterating again the group in case no member is up. */
1206
		if (!is_array($backupplan[$tier])) {
1207
			$backupplan[$tier] = array();
1208
		}
1209
		$backupplan[$tier][] = $gwname;
1210

    
1211
		/* check if the gateway is available before adding it to the array */
1212
		if (is_array($gateways_status[$gwname])) {
1213
			$status = $gateways_status[$gwname];
1214
			$gwdown = false;
1215
			if (stristr($status['status'], "down")) {
1216
				$msg = sprintf(gettext('MONITOR: %1$s is down, omitting from routing group %2$s'), $gwname, $group['name']);
1217
				$gwdown = true;
1218
			} else if (stristr($status['status'], "loss") && strstr($group['trigger'], "loss")) {
1219
				/* packet loss */
1220
				$msg = sprintf(gettext('MONITOR: %1$s has packet loss, omitting from routing group %2$s'), $gwname, $group['name']);
1221
				$gwdown = true;
1222
			} else if (stristr($status['status'], "delay") && strstr($group['trigger'] , "latency")) {
1223
				/* high latency */
1224
				$msg = sprintf(gettext('MONITOR: %1$s has high latency, omitting from routing group %2$s'), $gwname, $group['name']);
1225
				$gwdown = true;
1226
			}
1227
			$statuschanged = false;
1228
			$pluginparams = array();
1229
			$pluginparams['type'] = 'gateway';
1230
			$pluginparams['name'] = $gwname;
1231
			if ($gwdown == true) {
1232
				if (!file_exists("/tmp/.down.{$gwname}")) {
1233
					touch("/tmp/.down.{$gwname}");
1234
					$msg .= "\n".implode("|", $status);
1235
					$pluginparams['event'] = 'gateway.down';
1236
					$statuschanged = true;
1237
				}
1238
			} else {
1239
				/* Online add member */
1240
				if (!is_array($tiers[$tier])) {
1241
					$tiers[$tier] = array();
1242
				}
1243
				$tiers[$tier][] = $gwname;
1244
				if (unlink_if_exists("/tmp/.down.{$gwname}")) {
1245
					$msg = sprintf(getmypid () . gettext('MONITOR: %1$s is available now, adding to routing group %2$s'), $gwname, $group['name']);
1246
					$msg .= "\n".implode("|", $status);
1247
					$pluginparams['event'] = 'gateway.up';
1248
					$statuschanged = true;
1249
				}
1250
			}
1251
			if ($statuschanged) {
1252
				log_error($msg);
1253
				notify_via_growl($msg);
1254
				notify_via_smtp($msg);
1255
				if (isset($gateways_arr[$gwname]['interface'])) {
1256
					$pluginparams['interface'] = $gateways_arr[$gwname]['interface'];
1257
				}
1258
				pkg_call_plugins('plugin_gateway', $pluginparams);
1259
			}
1260
		} else if (isset($gateways_arr[$gwname]['monitor_disable']) || isset($gateways_arr[$gwname]['action_disable'])) {
1261
			$tiers[$tier][] = $gwname;
1262
		}
1263
	}
1264
	$tiers_count = count($tiers);
1265
	if ($tiers_count == 0) {
1266
		/* Oh dear, we have no members! Engage Plan B */
1267
		if (!platform_booting()) {
1268
			if (isset($config['system']['gw-debug'])) {
1269
				$msg = sprintf(gettext('Gateways status could not be determined, considering all as up/active. (Group: %s)'), $group['name']);
1270
				log_error($msg);
1271
				notify_via_growl($msg);
1272
				//notify_via_smtp($msg);
1273
			}
1274
		}
1275
		$tiers = $backupplan;
1276
	}
1277
	/* sort the tiers array by the tier key */
1278
	ksort($tiers);
1279

    
1280
	/* we do not really foreach the tiers as we stop after the first tier */
1281
	foreach ($tiers as $tieridx => $tier) {
1282
		/* process all gateways in this tier */
1283
		foreach ($tier as $member) {
1284
			/* determine interface gateway */
1285
			if (isset($gateways_arr[$member])) {
1286
				$gateway = $gateways_arr[$member];
1287
				$int = $gateway['interface'];
1288
				$gatewayip = "";
1289
				if (is_ipaddr($gateway['gateway'])) {
1290
					$gatewayip = $gateway['gateway'];
1291
				} else if (!empty($int)) {
1292
					$gatewayip = get_interface_gateway($gateway['friendlyiface']);
1293
				}
1294

    
1295
				if (!empty($int)) {
1296
					$result['ipprotocol'] = $gateway['ipprotocol'];
1297
					if (is_ipaddr($gatewayip)) {
1298
						$groupmember = array();
1299
						$groupmember['gw'] = $member;
1300
						$groupmember['int'] = $int;
1301
						$groupmember['gwip'] = $gatewayip;
1302
						$groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1;
1303
						if (is_array($gwvip_arr[$group['name']]) && !empty($gwvip_arr[$group['name']][$member])) {
1304
							$groupmember['vip'] = $gwvip_arr[$group['name']][$member];
1305
						}
1306
						$result[] = $groupmember;
1307
					}
1308
				}
1309
			}
1310
		}
1311
		/* we should have the 1st available tier now, exit stage left */
1312
		if (count($result) > 0) {
1313
			break;
1314
		} else {
1315
			log_error(sprintf(gettext('GATEWAYS: Group %1$s did not have any gateways up on tier %2$s!'), $group['name'], $tieridx));
1316
		}
1317
	}
1318
	// Add description field last to not influence the count() above
1319
	$result['descr'] = $group['descr'];
1320
	return $result;
1321
}
1322

    
1323
function get_gwgroup_members($groupname) {
1324
	global $config;
1325
	$gateways_status = return_gateways_status(true);
1326
	$gateways_arr = return_gateways_array();
1327
	$viplist = get_configured_vip_list();
1328
	foreach ($config['gateways']['gateway_group'] as $group) {
1329
		if ($group['name'] == $groupname) {
1330
			return get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1331
		}
1332
	}
1333
	return array();
1334
}
1335

    
1336
/*
1337
 * Return an array with all gateway groups with name as key
1338
 * All gateway groups will be processed before returning the array.
1339
 */
1340
function return_gateway_groups_array($fixup = false) {
1341
	global $config;
1342

    
1343
	/* fetch the current gateways status */
1344
	$gateways_status = return_gateways_status(true);
1345
	$gateways_arr = return_gateways_array();
1346
	$gateway_groups_array = array();
1347
	if ($fixup == true) {
1348
		$gw4 = lookup_gateway_or_group_by_name($config['gateways']['defaultgw4']);
1349
		$gw6 = lookup_gateway_or_group_by_name($config['gateways']['defaultgw6']);
1350
		if ($gw4 && $gw4['type'] == 'gatewaygroup') {
1351
			fixup_default_gateway("inet", $gateways_status, $gateways_arr);
1352
		}
1353
		if ($gw6 && $gw6['type'] == 'gatewaygroup') {
1354
			fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
1355
		}
1356
	}
1357
	if (is_array($config['gateways']['gateway_group'])) {
1358
		$viplist = get_configured_vip_list();
1359
		foreach ($config['gateways']['gateway_group'] as $group) {
1360
			$gateway_groups_array[$group['name']] = get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1361
		}
1362
	}
1363

    
1364
	return ($gateway_groups_array);
1365
}
1366

    
1367
/* Update DHCP WAN Interface ip address in gateway group item */
1368
function dhclient_update_gateway_groups_defaultroute($interface = "wan") {
1369
	global $config;
1370

    
1371
	if (is_array($config['gateways']['gateway_item'])) {
1372
		foreach ($config['gateways']['gateway_item'] as & $gw) {
1373
			if ($gw['interface'] != $interface) {
1374
				continue;
1375
			}
1376

    
1377
			$current_gw = get_interface_gateway($interface);
1378
			if ($gw['gateway'] <> $current_gw) {
1379
				$gw['gateway'] = $current_gw;
1380
				$changed = true;
1381
			}
1382
		}
1383
	}
1384

    
1385
	if ($changed && $current_gw) {
1386
		write_config(sprintf(gettext(
1387
		    'Updating gateway group gateway for %1$s - new gateway is %2$s'),
1388
		    $interface, $current_gw));
1389
	}
1390
}
1391

    
1392
function lookup_gateway_or_group_by_name($gwname) {
1393
	global $config;
1394

    
1395
	$gateways_arr = return_gateways_array();
1396
	foreach ($gateways_arr as $gw) {
1397
		if ($gw['name'] == $gwname) {
1398
			$gw['type'] = 'gateway';
1399
			return $gw;
1400
		}
1401
	}
1402

    
1403
	if (is_array($config['gateways']['gateway_group'])) {
1404
		foreach ($config['gateways']['gateway_group'] as $gwg) {
1405
			if ($gwg['name'] == $gwname) {
1406
				$gwg['type'] = 'gatewaygroup';
1407
				return $gwg;
1408
			}
1409
		}
1410
	}
1411

    
1412
	return false;
1413
}
1414

    
1415
function lookup_gateway_ip_by_name($name, $disabled = false) {
1416

    
1417
	$gateways_arr = return_gateways_array($disabled, true);
1418
	foreach ($gateways_arr as $gname => $gw) {
1419
		if ($gw['name'] === $name || $gname === $name) {
1420
			return $gw['gateway'];
1421
		}
1422
	}
1423

    
1424
	return false;
1425
}
1426

    
1427
function lookup_gateway_monitor_ip_by_name($name) {
1428

    
1429
	$gateways_arr = return_gateways_array(false, true);
1430
	if (!empty($gateways_arr[$name])) {
1431
		$gateway = $gateways_arr[$name];
1432
		if (!is_ipaddr($gateway['monitor'])) {
1433
			return $gateway['gateway'];
1434
		}
1435

    
1436
		return $gateway['monitor'];
1437
	}
1438

    
1439
	return (false);
1440
}
1441

    
1442
function lookup_gateway_interface_by_name($name) {
1443

    
1444
	$gateways_arr = return_gateways_array(false, true);
1445
	if (!empty($gateways_arr[$name])) {
1446
		$interfacegw = $gateways_arr[$name]['friendlyiface'];
1447
		return ($interfacegw);
1448
	}
1449

    
1450
	return (false);
1451
}
1452

    
1453
function get_root_interface($interface) {
1454
	if (substr($interface, 0, 4) == '_vip') {
1455
		$interface = get_configured_vip_interface($interface);
1456
		if (substr($interface, 0, 4) == '_vip') {
1457
			$interface = get_configured_vip_interface($interface);
1458
		}
1459
	}
1460
	return $interface;
1461
}
1462

    
1463
function get_interface_gateway($interface, &$dynamic = false) {
1464
	global $config, $g;
1465
	
1466
	$interface = get_root_interface($interface);
1467

    
1468
	$gw = NULL;
1469
	$gwcfg = $config['interfaces'][$interface];
1470
	if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) {
1471
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1472
			if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
1473
				$gw = $gateway['gateway'];
1474
				break;
1475
			}
1476
		}
1477
	}
1478

    
1479
	// for dynamic interfaces we handle them through the $interface_router file.
1480
	if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) {
1481
		$realif = get_real_interface($interface);
1482
		if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
1483
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
1484
			$dynamic = true;
1485
		}
1486
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) {
1487
			$dynamic = "default";
1488
		}
1489

    
1490
	}
1491

    
1492
	/* return gateway */
1493
	return ($gw);
1494
}
1495

    
1496
function get_interface_gateway_v6($interface, &$dynamic = false) {
1497
	global $config, $g;
1498

    
1499
	$interface = get_root_interface($interface);
1500

    
1501
	$gw = NULL;
1502
	$gwcfg = $config['interfaces'][$interface];
1503
	if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) {
1504
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1505
			if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
1506
				$gw = $gateway['gateway'];
1507
				break;
1508
			}
1509
		}
1510
	}
1511

    
1512
	// for dynamic interfaces we handle them through the $interface_router file.
1513
	if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) {
1514
		$realif = get_real_interface($interface);
1515
		if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
1516
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
1517
			$dynamic = true;
1518
		}
1519
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) {
1520
			$dynamic = "default";
1521
		}
1522
	}
1523
	/* return gateway */
1524
	return ($gw);
1525
}
1526

    
1527
/* Check a IP address against a gateway IP or name
1528
 * to verify it's address family */
1529
function validate_address_family($ipaddr, $gwname, $disabled = false) {
1530
	$v4ip = false;
1531
	$v6ip = false;
1532
	$v4gw = false;
1533
	$v6gw = false;
1534

    
1535
	if (is_ipaddrv4($ipaddr)) {
1536
		$v4ip = true;
1537
	}
1538
	if (is_ipaddrv6($ipaddr)) {
1539
		$v6ip = true;
1540
	}
1541
	if (is_ipaddrv4($gwname)) {
1542
		$v4gw = true;
1543
	}
1544
	if (is_ipaddrv6($gwname)) {
1545
		$v6gw = true;
1546
	}
1547

    
1548
	if ($v4ip && $v4gw) {
1549
		return true;
1550
	}
1551
	if ($v6ip && $v6gw) {
1552
		return true;
1553
	}
1554

    
1555
	/* still no match, carry on, lookup gateways */
1556
	if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname, $disabled))) {
1557
		$v4gw = true;
1558
	}
1559
	if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname, $disabled))) {
1560
		$v6gw = true;
1561
	}
1562

    
1563
	$gw_array = return_gateways_array();
1564
	if (is_array($gw_array[$gwname])) {
1565
		switch ($gw_array[$gwname]['ipprotocol']) {
1566
			case "inet":
1567
				$v4gw = true;
1568
				break;
1569
			case "inet6":
1570
				$v6gw = true;
1571
				break;
1572
		}
1573
	}
1574

    
1575
	if ($v4ip && $v4gw) {
1576
		return true;
1577
	}
1578
	if ($v6ip && $v6gw) {
1579
		return true;
1580
	}
1581

    
1582
	return false;
1583
}
1584

    
1585
/* check if a interface is part of a gateway group */
1586
function interface_gateway_group_member($interface, $gwgroup_name = "") {
1587
	global $config;
1588

    
1589
	if (is_array($config['gateways']['gateway_group'])) {
1590
		$groups = $config['gateways']['gateway_group'];
1591
	} else {
1592
		return false;
1593
	}
1594

    
1595
	$gateways_arr = return_gateways_array(false, true);
1596
	foreach ($groups as $group) {
1597
		if (is_array($group['item'])) {
1598
			foreach ($group['item'] as $item) {
1599
				$elements = explode("|", $item);
1600
				$gwname = $elements[0];
1601
				if ($interface == $gateways_arr[$gwname]['interface'] &&
1602
				    (empty($gwgroup_name) || $gwgroup_name == $group['name'])) {
1603
					unset($gateways_arr);
1604
					return true;
1605
				}
1606
			}
1607
		}
1608
	}
1609
	unset($gateways_arr);
1610

    
1611
	return false;
1612
}
1613

    
1614
function gateway_is_gwgroup_member($name, $detail=false) {
1615
	global $config;
1616

    
1617
	if (is_array($config['gateways']['gateway_group'])) {
1618
		$groups = $config['gateways']['gateway_group'];
1619
	} else {
1620
		return false;
1621
	}
1622

    
1623
	$members = array();
1624
	foreach ($groups as $group) {
1625
		if (is_array($group['item'])) {
1626
			foreach ($group['item'] as $item) {
1627
				list($gwname, $tier, $vipname) = explode("|", $item);
1628
				if ($name == $gwname) {
1629
					if ($detail) {
1630
						$newitem = array();
1631
						$newitem['name'] = $group['name'];
1632
						$newitem['tier'] = $tier;
1633
						$newitem['vipname'] = $vipname;
1634
						$members[] = $newitem;
1635
					} else {
1636
						$members[] = $group['name'];
1637
					}
1638
				}
1639
			}
1640
		}
1641
	}
1642

    
1643
	return $members;
1644
}
1645
/*
1646
  Check the proposed gateway settings to see if they are valid.
1647
  $gateway_settings - the proposed array of proposed gateway settings
1648
  $id - the index of the gateway proposed to be modified (otherwise "" if adding a new gateway)
1649
  $parent_ip - the IP (v4 or v6) address about to be set on the corresponding interface (if any)
1650
  $parent_sn - the subnet about to be set on the corresponding interface (if any)
1651
  (Note: the above 2 parameters allow gateway parameters to be validated concurrently with saving
1652
   an interface, before the new interface parameters are actually saved in the config.)
1653
  Return completed $input_errors array if there is any problem.
1654
  Otherwise return an empty $input_errors array
1655
*/
1656
function validate_gateway($gateway_settings, $id = "", $parent_ip = "", $parent_sn = "") {
1657
	global $config;
1658

    
1659
	$a_gateways = return_gateways_array(true, false, true, true);
1660
	$input_errors = array();
1661

    
1662
	/* input validation */
1663
	$reqdfields = explode(" ", "name interface");
1664
	$reqdfieldsn = array(gettext("Name"), gettext("Interface"));
1665

    
1666
	do_input_validation($gateway_settings, $reqdfields, $reqdfieldsn, $input_errors);
1667

    
1668
	if (!isset($gateway_settings['name'])) {
1669
		$input_errors[] = "A valid gateway name must be specified.";
1670
	}
1671
	if (!is_validaliasname($gateway_settings['name'])) {
1672
		$input_errors[] = invalidaliasnamemsg($gateway_settings['name'], gettext("gateway"));
1673
	} else if (isset($gateway_settings['disabled'])) {
1674
		// We have a valid gateway name that the user wants to mark as disabled.
1675
		// Check if the gateway name is used in any gateway group.
1676
		if (is_array($config['gateways']['gateway_group'])) {
1677
			foreach ($config['gateways']['gateway_group'] as $group) {
1678
				foreach ($group['item'] as $item) {
1679
					$items = explode("|", $item);
1680
					if ($items[0] == $gateway_settings['name']) {
1681
						$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']);
1682
					}
1683
				}
1684
			}
1685
		}
1686

    
1687
		// Check if the gateway name is used in any enabled Static Route.
1688
		if (is_array($config['staticroutes']['route'])) {
1689
			foreach ($config['staticroutes']['route'] as $route) {
1690
				if ($route['gateway'] == $gateway_settings['name']) {
1691
					if (!isset($route['disabled'])) {
1692
						// There is a static route that uses this gateway and is enabled (not disabled).
1693
						$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']);
1694
					}
1695
				}
1696
			}
1697
		}
1698
	}
1699
	/* skip system gateways which have been automatically added */
1700
	if (($gateway_settings['gateway'] && (!is_ipaddr($gateway_settings['gateway'])) && ($gateway_settings['attribute'] !== "system")) && ($gateway_settings['gateway'] != "dynamic")) {
1701
		$input_errors[] = gettext("A valid gateway IP address must be specified.");
1702
	}
1703

    
1704
	if ($gateway_settings['gateway'] && is_ipaddr($gateway_settings['gateway'])) {
1705
		if (is_ipaddrv4($gateway_settings['gateway'])) {
1706
			if ($parent_ip == '') {
1707
				$parent_ip = get_interface_ip($gateway_settings['interface']);
1708
				$parent_sn = get_interface_subnet($gateway_settings['interface']);
1709
			}
1710
			if (empty($parent_ip) || empty($parent_sn)) {
1711
				$input_errors[] = gettext("Cannot add IPv4 Gateway Address because no IPv4 address could be found on the interface.");
1712
			} elseif (!isset($gateway_settings["nonlocalgateway"])) {
1713
				$subnets = array(gen_subnet($parent_ip, $parent_sn) . "/" . $parent_sn);
1714
				$vips = link_interface_to_vips($gateway_settings['interface']);
1715
				if (is_array($vips)) {
1716
					foreach ($vips as $vip) {
1717
						if (!is_ipaddrv4($vip['subnet'])) {
1718
							continue;
1719
						}
1720
						$subnets[] = gen_subnet($vip['subnet'], $vip['subnet_bits']) . "/" . $vip['subnet_bits'];
1721
					}
1722
				}
1723

    
1724
				$found = false;
1725
				foreach ($subnets as $subnet) {
1726
					if (ip_in_subnet($gateway_settings['gateway'], $subnet)) {
1727
						$found = true;
1728
						break;
1729
					}
1730
				}
1731

    
1732
				if ($found === false) {
1733
					$input_errors[] = sprintf(gettext("The gateway address %s does not lie within one of the chosen interface's subnets."), $gateway_settings['gateway']);
1734
				}
1735
			}
1736
		} else if (is_ipaddrv6($gateway_settings['gateway'])) {
1737
			/* do not do a subnet match on a link local address, it's valid */
1738
			if (!is_linklocal($gateway_settings['gateway'])) {
1739
				if ($parent_ip == '') {
1740
					$parent_ip = get_interface_ipv6($gateway_settings['interface']);
1741
					$parent_sn = get_interface_subnetv6($gateway_settings['interface']);
1742
				}
1743
				if (empty($parent_ip) || empty($parent_sn)) {
1744
					$input_errors[] = gettext("Cannot add IPv6 Gateway Address because no IPv6 address could be found on the interface.");
1745
				} elseif (!isset($gateway_settings["nonlocalgateway"])) {
1746
					$subnets = array(gen_subnetv6($parent_ip, $parent_sn) . "/" . $parent_sn);
1747
					$vips = link_interface_to_vips($gateway_settings['interface']);
1748
					if (is_array($vips)) {
1749
						foreach ($vips as $vip) {
1750
							if (!is_ipaddrv6($vip['subnet'])) {
1751
								continue;
1752
							}
1753
							$subnets[] = gen_subnetv6($vip['subnet'], $vip['subnet_bits']) . "/" . $vip['subnet_bits'];
1754
						}
1755
					}
1756

    
1757
					$found = false;
1758
					foreach ($subnets as $subnet) {
1759
						if (ip_in_subnet($gateway_settings['gateway'], $subnet)) {
1760
							$found = true;
1761
							break;
1762
						}
1763
					}
1764

    
1765
					if ($found === false) {
1766
						$input_errors[] = sprintf(gettext("The gateway address %s does not lie within one of the chosen interface's subnets."), $gateway_settings['gateway']);
1767
					}
1768
				}
1769
			}
1770
		}
1771

    
1772
		if (!empty($config['interfaces'][$gateway_settings['interface']]['ipaddr'])) {
1773
			if (is_ipaddr($config['interfaces'][$gateway_settings['interface']]['ipaddr']) && (empty($gateway_settings['gateway']) || $gateway_settings['gateway'] == "dynamic")) {
1774
				$input_errors[] = gettext("Dynamic gateway values cannot be specified for interfaces with a static IPv4 configuration.");
1775
			}
1776
		}
1777
		if (!empty($config['interfaces'][$gateway_settings['interface']]['ipaddrv6'])) {
1778
			if (is_ipaddr($config['interfaces'][$gateway_settings['interface']]['ipaddrv6']) && (empty($gateway_settings['gateway']) || $gateway_settings['gateway'] == "dynamic")) {
1779
				$input_errors[] = gettext("Dynamic gateway values cannot be specified for interfaces with a static IPv6 configuration.");
1780
			}
1781
		}
1782
	}
1783
	if (($gateway_settings['monitor'] != "") && ($gateway_settings['monitor'] != "dynamic")) {
1784
		validateipaddr($gateway_settings['monitor'], IPV4V6, "Monitor IP", $input_errors, false);
1785
	}
1786
	if (isset($gateway_settings['data_payload']) && is_numeric($gateway_settings['data_payload']) && $gateway_settings['data_payload'] < 0) {
1787
		$input_errors[] = gettext("A valid data payload must be specified.");
1788
	}
1789
	/* only allow correct IPv4 and IPv6 gateway addresses */
1790
	if (($gateway_settings['gateway'] <> "") && is_ipaddr($gateway_settings['gateway']) && $gateway_settings['gateway'] != "dynamic") {
1791
		if (is_ipaddrv6($gateway_settings['gateway']) && ($gateway_settings['ipprotocol'] == "inet")) {
1792
			$input_errors[] = sprintf(gettext("The IPv6 gateway address '%s' can not be used as a IPv4 gateway."), $gateway_settings['gateway']);
1793
		}
1794
		if (is_ipaddrv4($gateway_settings['gateway']) && ($gateway_settings['ipprotocol'] == "inet6")) {
1795
			$input_errors[] = sprintf(gettext("The IPv4 gateway address '%s' can not be used as a IPv6 gateway."), $gateway_settings['gateway']);
1796
		}
1797
	}
1798
	/* only allow correct IPv4 and IPv6 monitor addresses */
1799
	if (($gateway_settings['monitor'] <> "") && is_ipaddr($gateway_settings['monitor']) && $gateway_settings['monitor'] != "dynamic") {
1800
		if (is_ipaddrv6($gateway_settings['monitor']) && ($gateway_settings['ipprotocol'] == "inet")) {
1801
			$input_errors[] = sprintf(gettext("The IPv6 monitor address '%s' can not be used on a IPv4 gateway."), $gateway_settings['monitor']);
1802
		}
1803
		if (is_ipaddrv4($gateway_settings['monitor']) && ($gateway_settings['ipprotocol'] == "inet6")) {
1804
			$input_errors[] = sprintf(gettext("The IPv4 monitor address '%s' can not be used on a IPv6 gateway."), $gateway_settings['monitor']);
1805
		}
1806
	}
1807

    
1808
	if (isset($gateway_settings['name'])) {
1809
		/* check for overlaps */
1810
		foreach ($a_gateways as $gateway) {
1811
			if (isset($id) && ($a_gateways[$id]) && ($a_gateways[$id] === $gateway)) {
1812
				if ($gateway['name'] != $gateway_settings['name']) {
1813
					$input_errors[] = gettext("Changing name on a gateway is not allowed.");
1814
				}
1815
				continue;
1816
			}
1817
			if ($gateway_settings['name'] <> "") {
1818
				if (($gateway['name'] <> "") && ($gateway_settings['name'] == $gateway['name']) && ($gateway['attribute'] !== "system")) {
1819
					$input_errors[] = sprintf(gettext('The gateway name "%s" already exists.'), $gateway_settings['name']);
1820
					break;
1821
				}
1822
			}
1823
			if (is_ipaddr($gateway_settings['gateway'])) {
1824
				if (($gateway['gateway'] <> "") && ($gateway_settings['gateway'] == $gateway['gateway']) && ($gateway['attribute'] !== "system")) {
1825
					$input_errors[] = sprintf(gettext('The gateway IP address "%s" already exists.'), $gateway_settings['gateway']);
1826
					break;
1827
				}
1828
			}
1829
			if (is_ipaddr($gateway_settings['monitor'])) {
1830
				if (($gateway['monitor'] <> "") && ($gateway_settings['monitor'] == $gateway['monitor']) && ($gateway['attribute'] !== "system")) {
1831
					$input_errors[] = sprintf(gettext('The monitor IP address "%s" is already in use. A different monitor IP must be chosen.'), $gateway_settings['monitor']);
1832
					break;
1833
				}
1834
			}
1835
		}
1836
	}
1837

    
1838
	/* input validation of dpinger advanced parameters */
1839

    
1840
	$dpinger_default = return_dpinger_defaults();
1841
	$latencylow = $dpinger_default['latencylow'];
1842
	if ($gateway_settings['latencylow']) {
1843
		if (!is_numeric($gateway_settings['latencylow'])) {
1844
			$input_errors[] = gettext("The low latency threshold needs to be a numeric value.");
1845
		} else if ($gateway_settings['latencylow'] < 1) {
1846
			$input_errors[] = gettext("The low latency threshold needs to be positive.");
1847
		} else {
1848
			$latencylow = $gateway_settings['latencylow'];
1849
		}
1850
	}
1851

    
1852
	$latencyhigh = $dpinger_default['latencyhigh'];
1853
	if ($gateway_settings['latencyhigh']) {
1854
		if (!is_numeric($gateway_settings['latencyhigh'])) {
1855
			$input_errors[] = gettext("The high latency threshold needs to be a numeric value.");
1856
		} else if ($gateway_settings['latencyhigh'] < 1) {
1857
			$input_errors[] = gettext("The high latency threshold needs to be positive.");
1858
		} else {
1859
			$latencyhigh = $gateway_settings['latencyhigh'];
1860
		}
1861
	}
1862

    
1863
	$losslow = $dpinger_default['losslow'];
1864
	if ($gateway_settings['losslow']) {
1865
		if (!is_numeric($gateway_settings['losslow'])) {
1866
			$input_errors[] = gettext("The low Packet Loss threshold needs to be a numeric value.");
1867
		} else if ($gateway_settings['losslow'] < 1) {
1868
			$input_errors[] = gettext("The low Packet Loss threshold needs to be positive.");
1869
		} else if ($gateway_settings['losslow'] >= 100) {
1870
			$input_errors[] = gettext("The low Packet Loss threshold needs to be less than 100.");
1871
		} else {
1872
			$losslow = $gateway_settings['losslow'];
1873
		}
1874
	}
1875

    
1876
	$losshigh = $dpinger_default['losshigh'];
1877
	if ($gateway_settings['losshigh']) {
1878
		if (!is_numeric($gateway_settings['losshigh'])) {
1879
			$input_errors[] = gettext("The high Packet Loss threshold needs to be a numeric value.");
1880
		} else if ($gateway_settings['losshigh'] < 1) {
1881
			$input_errors[] = gettext("The high Packet Loss threshold needs to be positive.");
1882
		} else if ($gateway_settings['losshigh'] > 100) {
1883
			$input_errors[] = gettext("The high Packet Loss threshold needs to be 100 or less.");
1884
		} else {
1885
			$losshigh = $gateway_settings['losshigh'];
1886
		}
1887
	}
1888

    
1889
	$time_period = $dpinger_default['time_period'];
1890
	if ($gateway_settings['time_period']) {
1891
		if (!is_numeric($gateway_settings['time_period'])) {
1892
			$input_errors[] = gettext("The time period over which results are averaged needs to be a numeric value.");
1893
		} else if ($gateway_settings['time_period'] < 1) {
1894
			$input_errors[] = gettext("The time period over which results are averaged needs to be positive.");
1895
		} else {
1896
			$time_period = $gateway_settings['time_period'];
1897
		}
1898
	}
1899

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

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

    
1922
	$alert_interval = $dpinger_default['alert_interval'];
1923
	if ($gateway_settings['alert_interval']) {
1924
		if (!is_numeric($gateway_settings['alert_interval'])) {
1925
			$input_errors[] = gettext("The alert interval needs to be a numeric value.");
1926
		} else if ($gateway_settings['alert_interval'] < 1) {
1927
			$input_errors[] = gettext("The alert interval setting needs to be positive.");
1928
		} else {
1929
			$alert_interval = $gateway_settings['alert_interval'];
1930
		}
1931
	}
1932

    
1933
	if ($latencylow >= $latencyhigh) {
1934
		$input_errors[] = gettext(
1935
		    "The high latency threshold needs to be greater than the low latency threshold");
1936
	}
1937

    
1938
	if ($losslow >= $losshigh) {
1939
		$input_errors[] = gettext(
1940
		    "The high packet loss threshold needs to be higher than the low packet loss threshold");
1941
	}
1942

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

    
1949
	// Ensure that the time period is greater than 2 times the probe interval plus the loss interval.
1950
	if (($interval * 2 + $loss_interval) >= $time_period) {
1951
		$input_errors[] = gettext("The time period needs to be greater than twice the probe interval plus the loss interval.");
1952
	}
1953

    
1954
	// There is no point recalculating the average latency and loss more often than the probe interval.
1955
	// So the alert interval needs to be >= probe interval.
1956
	if ($interval > $alert_interval) {
1957
		$input_errors[] = gettext("The alert interval needs to be greater than or equal to the probe interval.");
1958
	}
1959

    
1960
	return $input_errors;
1961
}
1962

    
1963
// Save gateway settings.
1964
// $gateway_settings - the array of gateway setting parameters
1965
// $realid - the index of the gateway to be modified (otherwise "" if adding a new gateway)
1966

    
1967
// This function is responsible to:
1968
//   Setup the gateway parameter structure from the gateway settings input parameter
1969
//   Save the structure into the config
1970
//   Remove any run-time settings from gateway parameters that are changed (e.g. remove routes to addresses that are changing)
1971

    
1972
// A subsequent "apply" step will implement the added/changed gateway.
1973

    
1974
function save_gateway($gateway_settings, $realid = "") {
1975
	global $config;
1976

    
1977
	if (!is_array($config['gateways'])) {
1978
		$config['gateways'] = array();
1979
	}
1980
	if (!is_array($config['gateways']['gateway_item'])) {
1981
		$config['gateways']['gateway_item'] = array();
1982
	}
1983
	$a_gateway_item = &$config['gateways']['gateway_item'];
1984
	$reloadif = "";
1985
	$gateway = array();
1986

    
1987
	if (empty($gateway_settings['interface'])) {
1988
		$gateway['interface'] = $gateway_settings['friendlyiface'];
1989
	} else {
1990
		$gateway['interface'] = $gateway_settings['interface'];
1991
	}
1992
	if (is_ipaddr($gateway_settings['gateway'])) {
1993
		$gateway['gateway'] = $gateway_settings['gateway'];
1994
	} else {
1995
		$gateway['gateway'] = "dynamic";
1996
	}
1997
	$gateway['name'] = $gateway_settings['name'];
1998
	$gateway['weight'] = $gateway_settings['weight'];
1999
	$gateway['ipprotocol'] = $gateway_settings['ipprotocol'];
2000
	if ($gateway_settings['interval']) {
2001
		$gateway['interval'] = $gateway_settings['interval'];
2002
	}
2003

    
2004
	if ($gateway_settings['time_period']) {
2005
		$gateway['time_period'] = $gateway_settings['time_period'];
2006
	}
2007
	if ($gateway_settings['alert_interval']) {
2008
		$gateway['alert_interval'] = $gateway_settings['alert_interval'];
2009
	}
2010

    
2011
	$gateway['descr'] = $gateway_settings['descr'];
2012
	if ($gateway_settings['monitor_disable'] == "yes") {
2013
		$gateway['monitor_disable'] = true;
2014
	}
2015
	if ($gateway_settings['action_disable'] == "yes") {
2016
		$gateway['action_disable'] = true;
2017
	}
2018
	if ($gateway_settings['nonlocalgateway'] == "yes") {
2019
		$gateway['nonlocalgateway'] = true;
2020
	}
2021
	if ($gateway_settings['force_down'] == "yes") {
2022
		$gateway['force_down'] = true;
2023
	}
2024
	if (is_ipaddr($gateway_settings['monitor'])) {
2025
		$gateway['monitor'] = $gateway_settings['monitor'];
2026
	}
2027
	if (isset($gateway_settings['data_payload']) && $gateway_settings['data_payload'] > 0) {
2028
		$gateway['data_payload'] = $gateway_settings['data_payload'];
2029
	}
2030

    
2031
	/* NOTE: If gateway ip is changed need to cleanup the old static interface route */
2032
	if ($gateway_settings['monitor'] != "dynamic" && !empty($a_gateway_item[$realid]) && is_ipaddr($a_gateway_item[$realid]['gateway']) &&
2033
		$gateway['gateway'] != $a_gateway_item[$realid]['gateway'] &&
2034
		isset($a_gateway_item[$realid]["nonlocalgateway"])) {
2035
		$realif = get_real_interface($a_gateway_item[$realid]['interface']);
2036
		$inet = (!is_ipaddrv4($a_gateway_item[$realid]['gateway']) ? "-inet6" : "-inet");
2037
		$cmd = "/sbin/route delete $inet " . escapeshellarg($a_gateway_item[$realid]['gateway']) . " -iface " . escapeshellarg($realif);
2038
		mwexec($cmd);
2039
	}
2040

    
2041
	/* NOTE: If monitor ip is changed need to cleanup the old static route */
2042
	if ($gateway_settings['monitor'] != "dynamic" && !empty($a_gateway_item[$realid]) && is_ipaddr($a_gateway_item[$realid]['monitor']) &&
2043
		$gateway_settings['monitor'] != $a_gateway_item[$realid]['monitor'] && $gateway['gateway'] != $a_gateway_item[$realid]['monitor']) {
2044
		if (is_ipaddrv4($a_gateway_item[$realid]['monitor'])) {
2045
			mwexec("/sbin/route delete " . escapeshellarg($a_gateway_item[$realid]['monitor']));
2046
		} else {
2047
			mwexec("/sbin/route delete -inet6 " . escapeshellarg($a_gateway_item[$realid]['monitor']));
2048
		}
2049
	}
2050

    
2051
	if ($gateway_settings['defaultgw'] == "yes" || $gateway_settings['defaultgw'] == "on") {
2052
		// a new default gateway is being saved.
2053
		$i = 0;
2054
		/* remove the default gateway bits for all gateways with the same address family */
2055
		if (is_array($a_gateway_item)) {
2056
			foreach ($a_gateway_item as $gw) {
2057
				if ($gateway['ipprotocol'] == $gw['ipprotocol']) {
2058
					if ($gw['interface'] != $gateway_settings['interface'] &&
2059
						($gw['name'] == $config['gateways']['defaultgw4'] || $gw['name'] == $config['gateways']['defaultgw6'])) {
2060
						// remember the old default gateway interface to call with a "interface reconfigure" event.
2061
						$reloadif = $gw['interface'];
2062
					}
2063
				}
2064
				$i++;
2065
			}
2066
		}
2067
		if ($gateway['ipprotocol'] == "inet") {
2068
			$config['gateways']['defaultgw4'] = $gateway['name'];
2069
		} elseif ($gateway['ipprotocol'] == "inet6") {
2070
			$config['gateways']['defaultgw6'] = $gateway['name'];
2071
		}
2072
	}
2073

    
2074
	if ($gateway_settings['latencylow']) {
2075
		$gateway['latencylow'] = $gateway_settings['latencylow'];
2076
	}
2077
	if ($gateway_settings['latencyhigh']) {
2078
		$gateway['latencyhigh'] = $gateway_settings['latencyhigh'];
2079
	}
2080
	if ($gateway_settings['losslow']) {
2081
		$gateway['losslow'] = $gateway_settings['losslow'];
2082
	}
2083
	if ($gateway_settings['losshigh']) {
2084
		$gateway['losshigh'] = $gateway_settings['losshigh'];
2085
	}
2086
	if ($gateway_settings['loss_interval']) {
2087
		$gateway['loss_interval'] = $gateway_settings['loss_interval'];
2088
	}
2089
	/* when saving the manual gateway we use the attribute which has the corresponding id */
2090
	if (isset($realid) && $a_gateway_item[$realid]) {
2091
		$preserve_disabled = isset($a_gateway_item[$realid]['disabled']);
2092
		$a_gateway_item[$realid] = $gateway;
2093
		if ($preserve_disabled) {
2094
			$a_gateway_item[$realid]['disabled'] = true;
2095
		}
2096
	} else {
2097
		$a_gateway_item[] = $gateway;
2098
	}
2099
	gateway_set_enabled($gateway_settings['name'], !isset($gateway_settings['disabled']));
2100

    
2101
	mark_subsystem_dirty('staticroutes');
2102

    
2103
	write_config();
2104

    
2105
	if (!empty($reloadif)) {
2106
		send_event("interface reconfigure {$reloadif}");
2107
	}
2108
}
2109

    
2110
function gateway_set_enabled($name, $enabled) {
2111
	global $config;
2112
	if (is_array($config['gateways']['gateway_item'])) {
2113
		foreach($config['gateways']['gateway_item'] as &$item) {
2114
			if ($item['name'] == $name) {
2115
				$gateway = &$item;
2116
			}
2117
		}
2118
	}
2119
	if (!isset($gateway)) {
2120
		return;
2121
	}
2122
	if ($enabled) {
2123
		unset($gateway['disabled']);
2124
	} else {
2125
		/* Check if the gateway was enabled but changed to disabled. */
2126
		if (!isset($gateway['disabled'])) {
2127
			/*  If the disabled gateway was the default route, remove the default route */
2128
			if (is_ipaddr($gateway['gateway'])) {
2129
				$inet = (!is_ipaddrv4($gateway['gateway']) ? 'inet6' : 'inet');
2130
				if ($inet == 'inet') {
2131
					$cgw = getcurrentdefaultgatewayip('inet');
2132
				} else {
2133
					$cgw = getcurrentdefaultgatewayip('inet6');
2134
				}
2135
				if ($gateway['gateway'] == $cgw) {
2136
					mwexec("/sbin/route delete -{$inet} default");
2137
				}
2138
			}
2139
			$gateway['disabled'] = true;
2140
		}
2141
	}
2142
}
2143

    
2144
function gateway_or_gwgroup_exists($name) {
2145
	global $config;
2146
	if (is_array($config['gateways']['gateway_item'])) {
2147
		foreach($config['gateways']['gateway_item'] as $item) {
2148
			if ($item['name'] == $name) {
2149
				return true;
2150
			}
2151
		}
2152
	}
2153
	if (is_array($config['gateways']['gateway_group'])) {
2154
		foreach($config['gateways']['gateway_group'] as $item) {
2155
			if ($item['name'] == $name) {
2156
				return true;
2157
			}
2158
		}
2159
	}
2160
	return false;
2161
}
2162

    
2163
?>
(22-22/60)