Project

General

Profile

Download (69.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * gwlb.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2008 Bill Marquette, Seth Mos
7
 * Copyright (c) 2008-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
/* Return all configured gateways on the system
548
   $disabled = true - include gateways that are disabled
549
   $localhost = true - include "Null" entries for localhost IP addresses
550
   $inactive = true - include gateways on inactive interfaces
551
   $integer_index = true - index the returned array by integers 0,1,2,... instead of by GW name
552
*/
553
function return_gateways_array($disabled = false, $localhost = false, $inactive = false, $integer_index = false) {
554
	global $config, $g;
555

    
556
	$gateways_arr = array();
557
	$gateways_arr_temp = array();
558
	$cgw4 = getcurrentdefaultgatewayip('inet');
559
	$cgw6 = getcurrentdefaultgatewayip('inet6');
560
	$found_defaultv4 = 0;
561
	$found_defaultv6 = 0;
562

    
563
	// Ensure the interface cache is up to date first
564
	$interfaces = get_interface_arr(true);
565

    
566
	$i = -1;
567
	/* Process/add all the configured gateways. */
568
	if (is_array($config['gateways']) && is_array($config['gateways']['gateway_item'])) {
569
		foreach ($config['gateways']['gateway_item'] as $gateway) {
570
			/* Increment it here to do not skip items */
571
			$i++;
572
			if (isset($gateway['defaultgw'])) {
573
				unset($gateway['defaultgw']);
574
			}
575

    
576
			if (empty($config['interfaces'][$gateway['interface']])) {
577
				if ($inactive === false) {
578
					continue;
579
				} else {
580
					$gateway['inactive'] = true;
581
				}
582
			}
583
			$wancfg = $config['interfaces'][$gateway['interface']];
584

    
585
			/* skip disabled interfaces */
586
			if ($disabled === false && (!isset($wancfg['enable']))) {
587
				continue;
588
			}
589

    
590
			/* if the gateway is dynamic and we can find the IPv4, Great! */
591
			if (empty($gateway['gateway']) || $gateway['gateway'] == "dynamic") {
592
				if ($gateway['ipprotocol'] == "inet") {
593
					/* we know which interfaces is dynamic, this should be made a function */
594
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
595
					/* no IP address found, set to dynamic */
596
					if (!is_ipaddrv4($gateway['gateway'])) {
597
						$gateway['gateway'] = "dynamic";
598
					}
599
					$gateway['dynamic'] = true;
600
				}
601

    
602
				/* if the gateway is dynamic and we can find the IPv6, Great! */
603
				else if ($gateway['ipprotocol'] == "inet6") {
604
					/* we know which interfaces is dynamic, this should be made a function, and for v6 too */
605
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
606
					/* no IPv6 address found, set to dynamic */
607
					if (!is_ipaddrv6($gateway['gateway'])) {
608
						$gateway['gateway'] = "dynamic";
609
					}
610
					$gateway['dynamic'] = true;
611
				}
612
			} else {
613
				/* getting this detection right is hard at this point because we still don't
614
				 * store the address family in the gateway item */
615
				if (is_ipaddrv4($gateway['gateway'])) {
616
					$gateway['ipprotocol'] = "inet";
617
				} else if (is_ipaddrv6($gateway['gateway'])) {
618
					$gateway['ipprotocol'] = "inet6";
619
				}
620
			}
621

    
622
			if (isset($gateway['monitor_disable'])) {
623
				$gateway['monitor_disable'] = true;
624
			} else if (empty($gateway['monitor'])) {
625
				$gateway['monitor'] = $gateway['gateway'];
626
			}
627

    
628
			if (isset($gateway['action_disable'])) {
629
				$gateway['action_disable'] = true;
630
			}
631

    
632
			$gateway['friendlyiface'] = $gateway['interface'];
633

    
634
			/* special treatment for tunnel interfaces */
635
			if ($gateway['ipprotocol'] == "inet6") {
636
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet6", false, false);
637
			} else {
638
				$gateway['interface'] = get_real_interface($gateway['interface'], "inet", false, false);
639
			}
640

    
641
			if ($gateway['ipprotocol'] == "inet" &&
642
					($config['gateways']['defaultgw4'] == $gateway['name'] || $gateway['gateway'] == $cgw4)) {
643
				$gateway['isdefaultgw'] = true;
644
				$found_defaultv4 = 1;
645
			} else if ($gateway['ipprotocol'] == "inet6" &&
646
					($config['gateways']['defaultgw6'] == $gateway['name'] || $gateway['gateway'] == $cgw6)) {
647
				$gateway['isdefaultgw'] = true;
648
				$found_defaultv6 = 1;
649
			}
650
			/* include the gateway index as the attribute */
651
			$gateway['attribute'] = $i;
652

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

    
657
			/* skip disabled gateways if the caller has not asked for them to be returned. */
658
			if (!($disabled === false && isset($gateway['disabled']))) {
659
				$gateways_arr[$gateway['name']] = $gateway;
660
			}
661
		}
662
	}
663
	unset($gateway);
664

    
665
	//Sort the array by GW name before moving on.
666
	ksort($gateways_arr, SORT_STRING | SORT_FLAG_CASE);
667

    
668
	/* Loop through all interfaces with a gateway and add it to a array */
669
	if ($disabled == false) {
670
		$iflist = get_configured_interface_with_descr();
671
	} else {
672
		$iflist = get_configured_interface_with_descr(true);
673
	}
674

    
675
	/* Process/add dynamic v4 gateways. */
676
	foreach ($iflist as $ifname => $friendly) {
677
		if (!interface_has_gateway($ifname)) {
678
			continue;
679
		}
680

    
681
		if (empty($config['interfaces'][$ifname])) {
682
			continue;
683
		}
684

    
685
		$ifcfg = &$config['interfaces'][$ifname];
686
		if (!isset($ifcfg['enable'])) {
687
			continue;
688
		}
689

    
690
		if (!empty($ifcfg['ipaddr']) && is_ipaddrv4($ifcfg['ipaddr'])) {
691
			continue;
692
		}
693

    
694
		$ctype = "";
695
		switch ($ifcfg['ipaddr']) {
696
			case "dhcp":
697
			case "pppoe":
698
			case "l2tp":
699
			case "pptp":
700
			case "ppp":
701
				$ctype = strtoupper($ifcfg['ipaddr']);
702
				break;
703
			default:
704
				$tunnelif = substr($ifcfg['if'], 0, 3);
705
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
706
					switch (substr($ifcfg['if'], 4, 1)) {
707
						case "c":
708
							$ovpntype = "openvpn-client";
709
							break;
710
						case "s":
711
							$ovpntype = "openvpn-server";
712
							break;
713
						default:
714
							// unknown ovpn type
715
							continue 2;
716
					}
717
					$ovpnid = substr($ifcfg['if'], 5);
718
					if (is_array($config['openvpn'][$ovpntype])) {
719
						foreach ($config['openvpn'][$ovpntype] as & $ovpnconf) {
720
							if ($ovpnconf['vpnid'] == $ovpnid) {
721
								// skip IPv6-only interfaces
722
								if ($ovpnconf['create_gw'] == "v6only") {
723
									continue 3;
724
								}
725
								// skip tap interfaces
726
								if ($ovpnconf['dev_mode'] == "tap") {
727
									continue 3;
728
								}
729
							}
730
						}
731
					}
732
					$ctype = "VPNv4";
733
				} elseif (substr($ifcfg['if'], 0, 5) == "ipsec") {
734
					$ikeid = substr($ifcfg['if'], 5);
735
					if (is_array($config['ipsec']) && is_array($config['ipsec']['phase1']) && is_array($config['ipsec']['phase2'])) {
736
						foreach ($config['ipsec']['phase1'] as $ph1ent) {
737
							if ($ph1ent['disabled']) {
738
								continue;
739
							}
740
							$vtisubnet_spec = ipsec_vti($ph1ent, true);
741
							// Skip non-VTI tunnels
742
							if (!$vtisubnet_spec || !is_array($vtisubnet_spec)) {
743
								continue;
744
							}
745
							if (!isset($ph1ent['mobile']) && ($keyexchange == 'ikev1' || isset($ph1ent['splitconn']))) {
746
								foreach ($vtisubnet_spec as $idx => $vtisub) {
747
									if ($ifcfg['if'] == "ipsec{$ph1ent['ikeid']}00{$idx}") {
748
										// If this specific VTI remote is v4, then we can make a v4 gw
749
										if (is_ipaddrv4($vtisub['right'])) {
750
											$ctype = "VTIv4";
751
										}
752
									}
753
								}
754
							} else {
755
								if ($ifcfg['if'] == "ipsec{$ph1ent['ikeid']}000") {
756
									// If any of the VTI remotes are v4, then we can make a v4 gw
757
									foreach ($vtisubnet_spec as $vtisub) {
758
										if (is_ipaddrv4($vtisub['right'])) {
759
											$ctype = "VTIv4";
760
										}
761
									}
762
								}
763
							}
764
						}
765
						if (empty($ctype)) {
766
							continue 2;
767
						}
768
					}
769
				} elseif ($tunnelif == "gif" || $tunnelif == "gre") {
770
					$ctype = "TUNNELv4";
771
				}
772
				break;
773
		}
774
		$ctype = "_". strtoupper($ctype);
775

    
776
		$gateway = array();
777
		$gateway['dynamic'] = false;
778
		$gateway['ipprotocol'] = "inet";
779
		$gateway['gateway'] = get_interface_gateway($ifname, $gateway['dynamic']);
780
		$gateway['interface'] = get_real_interface($ifname);
781
		$gateway['friendlyiface'] = $ifname;
782
		$gateway['name'] = "{$friendly}{$ctype}";
783
		$gateway['attribute'] = "system";
784

    
785
		if (($gateway['dynamic'] === "default") && ($found_defaultv4 == 0)) {
786
			$gateway['isdefaultgw'] = true;
787
			$gateway['dynamic'] = true;
788
			$found_defaultv4 = 1;
789
		}
790

    
791
		/* Loopback dummy for dynamic interfaces without a IP */
792
		if (!is_ipaddrv4($gateway['gateway']) && $gateway['dynamic'] == true) {
793
			$gateway['gateway'] = "dynamic";
794
		}
795

    
796
		/* automatically skip known static and dynamic gateways that were previously processed */
797
		foreach ($gateways_arr_temp as $gateway_item) {
798
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name'])&& ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
799
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
800
				continue 2;
801
			}
802
		}
803

    
804
		if (is_ipaddrv4($gateway['gateway'])) {
805
			$gateway['monitor'] = $gateway['gateway'];
806
		}
807

    
808
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
809
		$gateways_arr[$gateway['name']] = $gateway;
810
	}
811
	unset($gateway);
812

    
813
	/* Process/add dynamic v6 gateways. */
814
	foreach ($iflist as $ifname => $friendly) {
815
		/* If the user has disabled IPv6, they probably don't want any IPv6 gateways. */
816
		if (!isset($config['system']['ipv6allow'])) {
817
			break;
818
		}
819

    
820
		if (!interface_has_gatewayv6($ifname)) {
821
			continue;
822
		}
823

    
824
		if (empty($config['interfaces'][$ifname])) {
825
			continue;
826
		}
827

    
828
		$ifcfg = &$config['interfaces'][$ifname];
829
		if (!isset($ifcfg['enable'])) {
830
			continue;
831
		}
832

    
833
		if (!empty($ifcfg['ipaddrv6']) && is_ipaddrv6($ifcfg['ipaddrv6'])) {
834
			continue;
835
		}
836

    
837
		$ctype = "";
838
		switch ($ifcfg['ipaddrv6']) {
839
			case "slaac":
840
			case "dhcp6":
841
			case "6to4":
842
			case "6rd":
843
				$ctype = strtoupper($ifcfg['ipaddrv6']);
844
				break;
845
			default:
846
				$tunnelif = substr($ifcfg['if'], 0, 3);
847
				if (substr($ifcfg['if'], 0, 4) == "ovpn") {
848
					switch (substr($ifcfg['if'], 4, 1)) {
849
						case "c":
850
							$ovpntype = "openvpn-client";
851
							break;
852
						case "s":
853
							$ovpntype = "openvpn-server";
854
							break;
855
						default:
856
							// unknown ovpn type
857
							continue 2;
858
					}
859
					$ovpnid = substr($ifcfg['if'], 5);
860
					if (is_array($config['openvpn'][$ovpntype])) {
861
						foreach ($config['openvpn'][$ovpntype] as & $ovpnconf) {
862
							if ($ovpnconf['vpnid'] == $ovpnid) {
863
								// skip IPv4-only interfaces
864
								if ($ovpnconf['create_gw'] == "v4only") {
865
									continue 3;
866
								}
867
								// skip tap interfaces
868
								if ($ovpnconf['dev_mode'] == "tap") {
869
									continue 3;
870
								}
871
							}
872
						}
873
					}
874
					$ctype = "VPNv6";
875
				} elseif (substr($ifcfg['if'], 0, 5) == "ipsec") {
876
					$ikeid = substr($ifcfg['if'], 5);
877
					if (is_array($config['ipsec']) && is_array($config['ipsec']['phase1']) && is_array($config['ipsec']['phase2'])) {
878
						foreach ($config['ipsec']['phase1'] as $ph1ent) {
879
							if ($ph1ent['disabled']) {
880
								continue;
881
							}
882
							$vtisubnet_spec = ipsec_vti($ph1ent, true);
883
							// Skip non-VTI tunnels
884
							if (!$vtisubnet_spec || !is_array($vtisubnet_spec)) {
885
								continue;
886
							}
887
							if (!isset($ph1ent['mobile']) && ($keyexchange == 'ikev1' || isset($ph1ent['splitconn']))) {
888
								foreach ($vtisubnet_spec as $idx => $vtisub) {
889
									if ($ifcfg['if'] == "ipsec{$ph1ent['ikeid']}00{$idx}") {
890
										// If this specific VTI remote is v6, then we can make a v6 gw
891
										if (is_ipaddrv6($vtisub['right'])) {
892
											$ctype = "VTIv6";
893
										}
894
									}
895
								}
896
							} else {
897
								if ($ifcfg['if'] == "ipsec{$ph1ent['ikeid']}000") {
898
									// If any of the VTI remotes are v6, then we can make a v6 gw
899
									foreach ($vtisubnet_spec as $vtisub) {
900
										if (is_ipaddrv6($vtisub['right'])) {
901
											$ctype = "VTIv6";
902
										}
903
									}
904
								}
905
							}
906
						}
907
						if (empty($ctype)) {
908
							continue 2;
909
						}
910
					}
911
				} else if ($tunnelif == "gif" || $tunnelif == "gre") {
912
					$ctype = "TUNNELv6";
913
				}
914
				break;
915
		}
916
		$ctype = "_". strtoupper($ctype);
917

    
918
		$gateway = array();
919
		$gateway['dynamic'] = false;
920
		$gateway['ipprotocol'] = "inet6";
921
		$gateway['gateway'] = get_interface_gateway_v6($ifname, $gateway['dynamic']);
922
		$gateway['interface'] = get_real_interface($ifname, "inet6");
923
		switch ($ifcfg['ipaddrv6']) {
924
			case "6rd":
925
			case "6to4":
926
				$gateway['dynamic'] = "default";
927
				break;
928
		}
929
		$gateway['friendlyiface'] = $ifname;
930
		$gateway['name'] = "{$friendly}{$ctype}";
931
		$gateway['attribute'] = "system";
932

    
933
		if (($gateway['dynamic'] === "default") && ($found_defaultv6 == 0)) {
934
			$gateway['isdefaultgw'] = true;
935
			$gateway['dynamic'] = true;
936
			$found_defaultv6 = 1;
937
		}
938

    
939
		/* Loopback dummy for dynamic interfaces without a IP */
940
		if (!is_ipaddrv6($gateway['gateway']) && $gateway['dynamic'] == true) {
941
			$gateway['gateway'] = "dynamic";
942
		}
943

    
944
		/* automatically skip known static and dynamic gateways that were previously processed */
945
		foreach ($gateways_arr_temp as $gateway_item) {
946
			if ((($ifname == $gateway_item['friendlyiface'] && $friendly == $gateway_item['name']) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol'])) ||
947
			    (($ifname == $gateway_item['friendlyiface'] && $gateway_item['dynamic'] == true) && ($gateway['ipprotocol'] == $gateway_item['ipprotocol']))) {
948
				continue 2;
949
			}
950
		}
951

    
952
		if (is_ipaddrv6($gateway['gateway'])) {
953
			$gateway['monitor'] = $gateway['gateway'];
954
		}
955

    
956
		$gateway['descr'] = "Interface {$friendly}{$ctype} Gateway";
957
		$gateways_arr[$gateway['name']] = $gateway;
958
	}
959
	unset($gateway);
960

    
961
	/* FIXME: Should this be enabled.
962
	 * Some interface like wan might be default but have no info recorded
963
	 * the config. */
964
	/* this is a fallback if all else fails and we want to get packets out @smos */
965
	if ($found_defaultv4 == 0 || $found_defaultv6 == 0) {
966
		foreach ($gateways_arr as &$gateway) {
967
			if (($gateway['friendlyiface'] == "wan") && ($found_defaultv4 == 0) && (!isset($gateway['ipprotocol']) || ($gateway['ipprotocol'] == "inet"))) {
968
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgw")) {
969
					$gateway['isdefaultgw'] = true;
970
					$found_defaultv4 = 1;
971
				}
972
			}
973
			else if (($gateway['friendlyiface'] == "wan") && ($found_defaultv6 == 0) && ($gateway['ipprotocol'] == "inet6")) {
974
				if (file_exists("{$g['tmp_path']}/{$gateway['interface']}_defaultgwv6")) {
975
					$gateway['isdefaultgw'] = true;
976
					$found_defaultv6 = 1;
977
				}
978
			}
979
		}
980
	}
981

    
982
	if ($localhost === true) {
983
		/* attach localhost for Null routes */
984
		$gwlo4 = array();
985
		$gwlo4['name'] = "Null4";
986
		$gwlo4['interface'] = "lo0";
987
		$gwlo4['ipprotocol'] = "inet";
988
		$gwlo4['gateway'] = "127.0.0.1";
989
		$gwlo6 = array();
990
		$gwlo6['name'] = "Null6";
991
		$gwlo6['interface'] = "lo0";
992
		$gwlo6['ipprotocol'] = "inet6";
993
		$gwlo6['gateway'] = "::1";
994
		$gateways_arr['Null4'] = $gwlo4;
995
		$gateways_arr['Null6'] = $gwlo6;
996
	}
997

    
998
	if ($integer_index) {
999
		$gateways_arr = array_values($gateways_arr);
1000
	}
1001

    
1002
	if ($found_defaultv4 != 1 && is_ipaddr($cgw4)) {
1003
		foreach($gateways_arr as &$gw) {
1004
			if ($gw['gateway'] == $cgw4) {
1005
				$gw['isdefaultgw'] = true;
1006
			}
1007
		}
1008
	}
1009
	if ($found_defaultv6 != 1 && is_ipaddr($cgw6)) {
1010
		foreach($gateways_arr as &$gw) {
1011
			if ($gw['gateway'] == $cgw6) {
1012
				$gw['isdefaultgw'] = true;
1013
			}
1014
		}
1015
	}
1016
	return($gateways_arr);
1017
}
1018

    
1019
function fixup_default_gateway($ipprotocol, $gateways_status, $gateways_arr) {
1020
	global $config, $g;
1021
	/*
1022
	 * NOTE: The code below is meant to replace the default gateway when it goes down.
1023
	 *	This facilitates services running on pfSense itself and are not handled by a PBR to continue working.
1024
	 */
1025
	$upgw = '';
1026
	$dfltgwname = '';
1027
	$dfltgwdown = false;
1028
	$dfltgwfound = false;
1029

    
1030
	if ($ipprotocol == 'inet') {
1031
		$gwdefault = $config['gateways']['defaultgw4'];
1032
	} else {
1033
		$gwdefault = $config['gateways']['defaultgw6'];
1034
	}
1035
	if (isset($gateways_arr[$gwdefault])) {
1036
		// the configured gateway is a regular one. (not a gwgroup) use it as is..
1037
		$dfltgwname = $gwdefault;
1038
	} else {
1039
		// either a gwgroup is selected or gateway switching is used.
1040
		// find the best available gateway given options available..
1041
		if (!empty($gwdefault)) {
1042
			if (isset($gateways_status[$gwdefault])) {
1043
				$dfltgwfound = true;
1044
				$dfltgwname = $gwdefault;
1045
				if (!isset($gateways_arr['monitor_disable']) && !isset($gateways_arr['action_disable']) &&
1046
						$gateways_status[$gwdefault]['status'] != "none") {
1047
					$dfltgwdown = true;
1048
				}
1049
			} else {
1050
				$dfltgwfound = true;
1051

    
1052
				$viplist = get_configured_vip_list();
1053
				if (is_array($config['gateways']['gateway_group'])) {
1054
	 				foreach ($config['gateways']['gateway_group'] as $group) {
1055
						if ($group['name'] == $gwdefault) {
1056
							$gwgroup = get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1057
						}
1058
					}
1059
				}
1060

    
1061
				if (is_array($gwgroup)) {
1062
					if (count($gwgroup) > 0) {
1063
						$currentdefaultgwip = getcurrentdefaultgatewayip($ipprotocol);
1064
						$found_current = false;
1065
						foreach($gwgroup as $gwgroupitem) {
1066
							if ($gwgroupitem['gwip'] == $currentdefaultgwip) {
1067
								$dfltgwname = $gwgroupitem['gw'];
1068
								$found_current = true;
1069
								log_error("Keep current gateway, its already part of the group members.");
1070
								break;
1071
							}
1072
						}
1073
						if (!$found_current) {
1074
							$dfltgwname = $gwgroup[0]['gw'];
1075
							log_error(sprintf("Gateway, switch to: %s", $dfltgwname));
1076
						}
1077
					} else {
1078
						log_error("Gateway, NONE AVAILABLE");
1079
						$dfltgwdown = true;
1080
					}
1081
				}
1082
			}
1083
		}
1084
		if ($dfltgwdown) {
1085
			foreach ($gateways_arr as $gwname => $gwsttng) {
1086
				/* Keep a record of the last up gateway */
1087
				/* XXX: Blacklist lan for now since it might cause issues to those who have a gateway set for it */
1088
				if (empty($upgw) && ($gwsttng['ipprotocol'] == $ipprotocol) &&
1089
						(isset($gwsttng['monitor_disable']) ||
1090
						isset($gwsttng['action_disable']) ||
1091
						$gateways_status[$gwname]['status'] == "none"
1092
						) &&
1093
						$gwsttng[$gwname]['friendlyiface'] != "lan") {
1094
					$upgw = $gwname;
1095
				}
1096
				if ($dfltgwdown == true && !empty($upgw)) {
1097
					break;
1098
				}
1099
			}
1100
		}
1101
		if ($dfltgwfound == false) {
1102
			$gwname = convert_friendly_interface_to_friendly_descr("wan");
1103
			if (!empty($gateways_status[$gwname]) && stristr($gateways_status[$gwname]['status'], "down")) {
1104
				$dfltgwdown = true;
1105
			}
1106
		}
1107
	}
1108
	if ($dfltgwdown == true && !empty($upgw)) {
1109
		setdefaultgateway($gateways_arr[$upgw]);
1110
	} else if (!empty($dfltgwname)) {
1111
		setdefaultgateway($gateways_arr[$dfltgwname]);
1112
	}
1113
}
1114

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

    
1119
function setdefaultgateway($gw) {
1120
	global $g;
1121
	if (isset($config['system']['route-debug'])) {
1122
		file_put_contents("/dev/console", "\n[".getmypid()."] SET DEF GW: {$gw['name']}");
1123
	}
1124
	$ipprotocol = $gw['ipprotocol'];
1125
	if ($gw['gateway'] == "dynamic") {
1126
		if ($ipprotocol == 'inet') {
1127
			$gw['gateway'] = get_interface_gateway($gw['friendlyiface']);
1128
		} else {
1129
			$gw['gateway'] = get_interface_gateway_v6($$gw['friendlyiface']);
1130
		}
1131
	}
1132
	if ($ipprotocol == 'inet6' && !is_ipaddrv6($gw['gateway'])) {
1133
		return;
1134
	}
1135
	if ($ipprotocol == 'inet' && !is_ipaddrv4($gw['gateway'])) {
1136
		return;
1137
	}
1138
	if ($ipprotocol == 'inet6') {
1139
		if (is_linklocal($gw['gateway']) && get_ll_scope($gw['gateway']) == '') {
1140
			$gw['gateway'] .= "%" . $gw['interface'];
1141
		}
1142
	}
1143
	$currentdefaultgwip = getcurrentdefaultgatewayip($ipprotocol);
1144
	if ($currentdefaultgwip != $gw['gateway']) {
1145
		log_error("Default gateway setting {$gw['descr']} as default.");
1146

    
1147
		if ($ipprotocol == 'inet') {
1148
			array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw", GLOB_BRACE));
1149
		} else {
1150
			array_map('unlink', glob("{$g['tmp_path']}/*_defaultgwv6", GLOB_BRACE));
1151
		}
1152
		$defaultif = get_real_interface($gw['interface']);
1153
		if ($defaultif) {
1154
			@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gw['gateway']);
1155
		}
1156

    
1157
		if (isset($gw["nonlocalgateway"])) {
1158
			if (is_ipaddr($gw['gateway']) && !empty($gw['interface'])) {
1159
				route_add_or_change("-{$ipprotocol} {$gw['gateway']} -iface {$gw['interface']}");
1160
			}
1161
		}
1162
		if (isset($config['system']['route-debug'])) {
1163
			file_put_contents("/dev/console", "\n[".getmypid()."] SET DEF GW: {$gw['name']} ({$gw['gateway']})");
1164
		}
1165
		route_add_or_change("-{$ipprotocol} default {$gw['gateway']}");
1166
		return true;
1167
	}
1168
}
1169

    
1170
function get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist){
1171
	$result = array();
1172
	/* create array with group gateways members separated by tier */
1173
	$tiers = array();
1174
	$backupplan = array();
1175
	$gwvip_arr = array();
1176
	foreach ($group['item'] as $item) {
1177
		list($gwname, $tier, $vipname) = explode("|", $item);
1178

    
1179
		if (is_ipaddr($viplist[$vipname])) {
1180
			if (!is_array($gwvip_arr[$group['name']])) {
1181
				$gwvip_arr[$group['name']] = array();
1182
			}
1183
			$gwvip_arr[$group['name']][$gwname] = $vipname;
1184
		}
1185

    
1186
		/* Do it here rather than reiterating again the group in case no member is up. */
1187
		if (!is_array($backupplan[$tier])) {
1188
			$backupplan[$tier] = array();
1189
		}
1190
		$backupplan[$tier][] = $gwname;
1191

    
1192
		/* check if the gateway is available before adding it to the array */
1193
		if (is_array($gateways_status[$gwname])) {
1194
			$status = $gateways_status[$gwname];
1195
			$gwdown = false;
1196
			if (stristr($status['status'], "down")) {
1197
				$msg = sprintf(gettext('MONITOR: %1$s is down, omitting from routing group %2$s'), $gwname, $group['name']);
1198
				$gwdown = true;
1199
			} else if (stristr($status['status'], "loss") && strstr($group['trigger'], "loss")) {
1200
				/* packet loss */
1201
				$msg = sprintf(gettext('MONITOR: %1$s has packet loss, omitting from routing group %2$s'), $gwname, $group['name']);
1202
				$gwdown = true;
1203
			} else if (stristr($status['status'], "delay") && strstr($group['trigger'] , "latency")) {
1204
				/* high latency */
1205
				$msg = sprintf(gettext('MONITOR: %1$s has high latency, omitting from routing group %2$s'), $gwname, $group['name']);
1206
				$gwdown = true;
1207
			}
1208
			$statuschanged = false;
1209
			$pluginparams = array();
1210
			$pluginparams['type'] = 'gateway';
1211
			$pluginparams['name'] = ${gwname};
1212
			if ($gwdown == true) {
1213
				if (!file_exists("/tmp/.down.{$gwname}")) {
1214
					touch("/tmp/.down.{$gwname}");
1215
					$msg .= "\n".implode("|", $status);
1216
					$pluginparams['event'] = 'gateway.down';
1217
					$statuschanged = true;
1218
				}
1219
			} else {
1220
				/* Online add member */
1221
				if (!is_array($tiers[$tier])) {
1222
					$tiers[$tier] = array();
1223
				}
1224
				$tiers[$tier][] = $gwname;
1225
				if (unlink_if_exists("/tmp/.down.{$gwname}")) {
1226
					$msg = sprintf(getmypid () . gettext('MONITOR: %1$s is available now, adding to routing group %2$s'), $gwname, $group['name']);
1227
					$msg .= "\n".implode("|", $status);
1228
					$pluginparams['event'] = 'gateway.up';
1229
					$statuschanged = true;
1230
				}
1231
			}
1232
			if ($statuschanged) {
1233
				log_error($msg);
1234
				notify_via_growl($msg);
1235
				notify_via_smtp($msg);
1236
				if (isset($gateways_arr[$gwname]['interface'])) {
1237
					$pluginparams['interface'] = $gateways_arr[$gwname]['interface'];
1238
				}
1239
				pkg_call_plugins('plugin_gateway', $pluginparams);
1240
			}
1241
		} else if (isset($gateways_arr[$gwname]['monitor_disable']) || isset($gateways_arr[$gwname]['action_disable'])) {
1242
			$tiers[$tier][] = $gwname;
1243
		}
1244
	}
1245
	$tiers_count = count($tiers);
1246
	if ($tiers_count == 0) {
1247
		/* Oh dear, we have no members! Engage Plan B */
1248
		if (!platform_booting()) {
1249
			$msg = sprintf(gettext('Gateways status could not be determined, considering all as up/active. (Group: %s)'), $group['name']);
1250
			log_error($msg);
1251
			notify_via_growl($msg);
1252
			//notify_via_smtp($msg);
1253
		}
1254
		$tiers = $backupplan;
1255
	}
1256
	/* sort the tiers array by the tier key */
1257
	ksort($tiers);
1258

    
1259
	/* we do not really foreach the tiers as we stop after the first tier */
1260
	foreach ($tiers as $tieridx => $tier) {
1261
		/* process all gateways in this tier */
1262
		foreach ($tier as $member) {
1263
			/* determine interface gateway */
1264
			if (isset($gateways_arr[$member])) {
1265
				$gateway = $gateways_arr[$member];
1266
				$int = $gateway['interface'];
1267
				$gatewayip = "";
1268
				if (is_ipaddr($gateway['gateway'])) {
1269
					$gatewayip = $gateway['gateway'];
1270
				} else if (!empty($int)) {
1271
					$gatewayip = get_interface_gateway($gateway['friendlyiface']);
1272
				}
1273

    
1274
				if (!empty($int)) {
1275
					$result['ipprotocol'] = $gateway['ipprotocol'];
1276
					if (is_ipaddr($gatewayip)) {
1277
						$groupmember = array();
1278
						$groupmember['gw'] = $member;
1279
						$groupmember['int'] = $int;
1280
						$groupmember['gwip'] = $gatewayip;
1281
						$groupmember['weight'] = isset($gateway['weight']) ? $gateway['weight'] : 1;
1282
						if (is_array($gwvip_arr[$group['name']]) && !empty($gwvip_arr[$group['name']][$member])) {
1283
							$groupmember['vip'] = $gwvip_arr[$group['name']][$member];
1284
						}
1285
						$result[] = $groupmember;
1286
					}
1287
				}
1288
			}
1289
		}
1290
		/* we should have the 1st available tier now, exit stage left */
1291
		if (count($result) > 0) {
1292
			break;
1293
		} else {
1294
			log_error(sprintf(gettext('GATEWAYS: Group %1$s did not have any gateways up on tier %2$s!'), $group['name'], $tieridx));
1295
		}
1296
	}
1297
	// Add description field last to not influence the count() above
1298
	$result['descr'] = $group['descr'];
1299
	return $result;
1300
}
1301

    
1302
function get_gwgroup_members($groupname) {
1303
	global $config;
1304
	$gateways_status = return_gateways_status(true);
1305
	$gateways_arr = return_gateways_array();
1306
	$viplist = get_configured_vip_list();
1307
	foreach ($config['gateways']['gateway_group'] as $group) {
1308
		if ($group['name'] == $groupname) {
1309
			return get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1310
		}
1311
	}
1312
	return array();
1313
}
1314

    
1315
/*
1316
 * Return an array with all gateway groups with name as key
1317
 * All gateway groups will be processed before returning the array.
1318
 */
1319
function return_gateway_groups_array($fixup = false) {
1320
	global $config;
1321

    
1322
	/* fetch the current gateways status */
1323
	$gateways_status = return_gateways_status(true);
1324
	$gateways_arr = return_gateways_array();
1325
	$gateway_groups_array = array();
1326
	if ($fixup == true) {
1327
		$gw4 = lookup_gateway_or_group_by_name($config['gateways']['defaultgw4']);
1328
		$gw6 = lookup_gateway_or_group_by_name($config['gateways']['defaultgw6']);
1329
		if ($gw4 && $gw4['type'] == 'gatewaygroup') {
1330
			fixup_default_gateway("inet", $gateways_status, $gateways_arr);
1331
		}
1332
		if ($gw6 && $gw6['type'] == 'gatewaygroup') {
1333
			fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
1334
		}
1335
	}
1336
	if (is_array($config['gateways']['gateway_group'])) {
1337
		$viplist = get_configured_vip_list();
1338
		foreach ($config['gateways']['gateway_group'] as $group) {
1339
			$gateway_groups_array[$group['name']] = get_gwgroup_members_inner($group, $gateways_status, $gateways_arr, $viplist);
1340
		}
1341
	}
1342

    
1343
	return ($gateway_groups_array);
1344
}
1345

    
1346
/* Update DHCP WAN Interface ip address in gateway group item */
1347
function dhclient_update_gateway_groups_defaultroute($interface = "wan") {
1348
	global $config;
1349

    
1350
	if (is_array($config['gateways']['gateway_item'])) {
1351
		foreach ($config['gateways']['gateway_item'] as & $gw) {
1352
			if ($gw['interface'] != $interface) {
1353
				continue;
1354
			}
1355

    
1356
			$current_gw = get_interface_gateway($interface);
1357
			if ($gw['gateway'] <> $current_gw) {
1358
				$gw['gateway'] = $current_gw;
1359
				$changed = true;
1360
			}
1361
		}
1362
	}
1363

    
1364
	if ($changed && $current_gw) {
1365
		write_config(sprintf(gettext(
1366
		    'Updating gateway group gateway for %1$s - new gateway is %2$s'),
1367
		    $interface, $current_gw));
1368
	}
1369
}
1370

    
1371
function lookup_gateway_or_group_by_name($gwname) {
1372
	global $config;
1373

    
1374
	if (is_array($config['gateways']['gateway_item'])) {
1375
		foreach ($config['gateways']['gateway_item'] as $gw) {
1376
			if ($gw['name'] == $gwname) {
1377
				$gw['type'] = 'gateway';
1378
				return $gw;
1379
			}
1380
		}
1381
	}
1382

    
1383
	if (is_array($config['gateways']['gateway_group'])) {
1384
		foreach ($config['gateways']['gateway_group'] as $gwg) {
1385
			if ($gwg['name'] == $gwname) {
1386
				$gwg['type'] = 'gatewaygroup';
1387
				return $gwg;
1388
			}
1389
		}
1390
	}
1391

    
1392
	return false;
1393
}
1394

    
1395
function lookup_gateway_ip_by_name($name, $disabled = false) {
1396

    
1397
	$gateways_arr = return_gateways_array($disabled, true);
1398
	foreach ($gateways_arr as $gname => $gw) {
1399
		if ($gw['name'] === $name || $gname === $name) {
1400
			return $gw['gateway'];
1401
		}
1402
	}
1403

    
1404
	return false;
1405
}
1406

    
1407
function lookup_gateway_monitor_ip_by_name($name) {
1408

    
1409
	$gateways_arr = return_gateways_array(false, true);
1410
	if (!empty($gateways_arr[$name])) {
1411
		$gateway = $gateways_arr[$name];
1412
		if (!is_ipaddr($gateway['monitor'])) {
1413
			return $gateway['gateway'];
1414
		}
1415

    
1416
		return $gateway['monitor'];
1417
	}
1418

    
1419
	return (false);
1420
}
1421

    
1422
function lookup_gateway_interface_by_name($name) {
1423

    
1424
	$gateways_arr = return_gateways_array(false, true);
1425
	if (!empty($gateways_arr[$name])) {
1426
		$interfacegw = $gateways_arr[$name]['friendlyiface'];
1427
		return ($interfacegw);
1428
	}
1429

    
1430
	return (false);
1431
}
1432

    
1433
function get_interface_gateway($interface, &$dynamic = false) {
1434
	global $config, $g;
1435

    
1436
	if (substr($interface, 0, 4) == '_vip') {
1437
		$interface = get_configured_vip_interface($interface);
1438
		if (substr($interface, 0, 4) == '_vip') {
1439
			$interface = get_configured_vip_interface($interface);
1440
		}
1441
	}
1442

    
1443
	$gw = NULL;
1444
	$gwcfg = $config['interfaces'][$interface];
1445
	if (!empty($gwcfg['gateway']) && is_array($config['gateways']['gateway_item'])) {
1446
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1447
			if (($gateway['name'] == $gwcfg['gateway']) && (is_ipaddrv4($gateway['gateway']))) {
1448
				$gw = $gateway['gateway'];
1449
				break;
1450
			}
1451
		}
1452
	}
1453

    
1454
	// for dynamic interfaces we handle them through the $interface_router file.
1455
	if (($gw == NULL || !is_ipaddrv4($gw)) && !is_ipaddrv4($gwcfg['ipaddr'])) {
1456
		$realif = get_real_interface($interface);
1457
		if (file_exists("{$g['tmp_path']}/{$realif}_router")) {
1458
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_router"), " \n");
1459
			$dynamic = true;
1460
		}
1461
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgw")) {
1462
			$dynamic = "default";
1463
		}
1464

    
1465
	}
1466

    
1467
	/* return gateway */
1468
	return ($gw);
1469
}
1470

    
1471
function get_interface_gateway_v6($interface, &$dynamic = false) {
1472
	global $config, $g;
1473

    
1474
	if (substr($interface, 0, 4) == '_vip') {
1475
		$interface = get_configured_vip_interface($interface);
1476
		if (substr($interface, 0, 4) == '_vip') {
1477
			$interface = get_configured_vip_interface($interface);
1478
		}
1479
	}
1480

    
1481
	$gw = NULL;
1482
	$gwcfg = $config['interfaces'][$interface];
1483
	if (!empty($gwcfg['gatewayv6']) && is_array($config['gateways']['gateway_item'])) {
1484
		foreach ($config['gateways']['gateway_item'] as $gateway) {
1485
			if (($gateway['name'] == $gwcfg['gatewayv6']) && (is_ipaddrv6($gateway['gateway']))) {
1486
				$gw = $gateway['gateway'];
1487
				break;
1488
			}
1489
		}
1490
	}
1491

    
1492
	// for dynamic interfaces we handle them through the $interface_router file.
1493
	if (($gw == NULL || !is_ipaddrv6($gw)) && !is_ipaddrv6($gwcfg['ipaddrv6'])) {
1494
		$realif = get_real_interface($interface);
1495
		if (file_exists("{$g['tmp_path']}/{$realif}_routerv6")) {
1496
			$gw = trim(file_get_contents("{$g['tmp_path']}/{$realif}_routerv6"), " \n");
1497
			$dynamic = true;
1498
		}
1499
		if (file_exists("{$g['tmp_path']}/{$realif}_defaultgwv6")) {
1500
			$dynamic = "default";
1501
		}
1502
	}
1503
	/* return gateway */
1504
	return ($gw);
1505
}
1506

    
1507
/* Check a IP address against a gateway IP or name
1508
 * to verify it's address family */
1509
function validate_address_family($ipaddr, $gwname, $disabled = false) {
1510
	$v4ip = false;
1511
	$v6ip = false;
1512
	$v4gw = false;
1513
	$v6gw = false;
1514

    
1515
	if (is_ipaddrv4($ipaddr)) {
1516
		$v4ip = true;
1517
	}
1518
	if (is_ipaddrv6($ipaddr)) {
1519
		$v6ip = true;
1520
	}
1521
	if (is_ipaddrv4($gwname)) {
1522
		$v4gw = true;
1523
	}
1524
	if (is_ipaddrv6($gwname)) {
1525
		$v6gw = true;
1526
	}
1527

    
1528
	if ($v4ip && $v4gw) {
1529
		return true;
1530
	}
1531
	if ($v6ip && $v6gw) {
1532
		return true;
1533
	}
1534

    
1535
	/* still no match, carry on, lookup gateways */
1536
	if (is_ipaddrv4(lookup_gateway_ip_by_name($gwname, $disabled))) {
1537
		$v4gw = true;
1538
	}
1539
	if (is_ipaddrv6(lookup_gateway_ip_by_name($gwname, $disabled))) {
1540
		$v6gw = true;
1541
	}
1542

    
1543
	$gw_array = return_gateways_array();
1544
	if (is_array($gw_array[$gwname])) {
1545
		switch ($gw_array[$gwname]['ipprotocol']) {
1546
			case "inet":
1547
				$v4gw = true;
1548
				break;
1549
			case "inet6":
1550
				$v6gw = true;
1551
				break;
1552
		}
1553
	}
1554

    
1555
	if ($v4ip && $v4gw) {
1556
		return true;
1557
	}
1558
	if ($v6ip && $v6gw) {
1559
		return true;
1560
	}
1561

    
1562
	return false;
1563
}
1564

    
1565
/* check if a interface is part of a gateway group */
1566
function interface_gateway_group_member($interface, $gwgroup_name = "") {
1567
	global $config;
1568

    
1569
	if (is_array($config['gateways']['gateway_group'])) {
1570
		$groups = $config['gateways']['gateway_group'];
1571
	} else {
1572
		return false;
1573
	}
1574

    
1575
	$gateways_arr = return_gateways_array(false, true);
1576
	foreach ($groups as $group) {
1577
		if (is_array($group['item'])) {
1578
			foreach ($group['item'] as $item) {
1579
				$elements = explode("|", $item);
1580
				$gwname = $elements[0];
1581
				if ($interface == $gateways_arr[$gwname]['interface'] &&
1582
				    (empty($gwgroup_name) || $gwgroup_name == $group['name'])) {
1583
					unset($gateways_arr);
1584
					return true;
1585
				}
1586
			}
1587
		}
1588
	}
1589
	unset($gateways_arr);
1590

    
1591
	return false;
1592
}
1593

    
1594
function gateway_is_gwgroup_member($name, $detail=false) {
1595
	global $config;
1596

    
1597
	if (is_array($config['gateways']['gateway_group'])) {
1598
		$groups = $config['gateways']['gateway_group'];
1599
	} else {
1600
		return false;
1601
	}
1602

    
1603
	$members = array();
1604
	foreach ($groups as $group) {
1605
		if (is_array($group['item'])) {
1606
			foreach ($group['item'] as $item) {
1607
				list($gwname, $tier, $vipname) = explode("|", $item);
1608
				if ($name == $gwname) {
1609
					if ($detail) {
1610
						$newitem = array();
1611
						$newitem['name'] = $group['name'];
1612
						$newitem['tier'] = $tier;
1613
						$newitem['vipname'] = $vipname;
1614
						$members[] = $newitem;
1615
					} else {
1616
						$members[] = $group['name'];
1617
					}
1618
				}
1619
			}
1620
		}
1621
	}
1622

    
1623
	return $members;
1624
}
1625
/*
1626
  Check the proposed gateway settings to see if they are valid.
1627
  $gateway_settings - the proposed array of proposed gateway settings
1628
  $id - the index of the gateway proposed to be modified (otherwise "" if adding a new gateway)
1629
  $parent_ip - the IP (v4 or v6) address about to be set on the corresponding interface (if any)
1630
  $parent_sn - the subnet about to be set on the corresponding interface (if any)
1631
  (Note: the above 2 parameters allow gateway parameters to be validated concurrently with saving
1632
   an interface, before the new interface parameters are actually saved in the config.)
1633
  Return completed $input_errors array if there is any problem.
1634
  Otherwise return an empty $input_errors array
1635
*/
1636
function validate_gateway($gateway_settings, $id = "", $parent_ip = "", $parent_sn = "") {
1637
	global $config;
1638

    
1639
	$a_gateways = return_gateways_array(true, false, true, true);
1640
	$input_errors = array();
1641

    
1642
	/* input validation */
1643
	$reqdfields = explode(" ", "name interface");
1644
	$reqdfieldsn = array(gettext("Name"), gettext("Interface"));
1645

    
1646
	do_input_validation($gateway_settings, $reqdfields, $reqdfieldsn, $input_errors);
1647

    
1648
	if (!isset($gateway_settings['name'])) {
1649
		$input_errors[] = "A valid gateway name must be specified.";
1650
	}
1651
	if (!is_validaliasname($gateway_settings['name'])) {
1652
		$input_errors[] = invalidaliasnamemsg($gateway_settings['name'], gettext("gateway"));
1653
	} else if (isset($gateway_settings['disabled'])) {
1654
		// We have a valid gateway name that the user wants to mark as disabled.
1655
		// Check if the gateway name is used in any gateway group.
1656
		if (is_array($config['gateways']['gateway_group'])) {
1657
			foreach ($config['gateways']['gateway_group'] as $group) {
1658
				foreach ($group['item'] as $item) {
1659
					$items = explode("|", $item);
1660
					if ($items[0] == $gateway_settings['name']) {
1661
						$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']);
1662
					}
1663
				}
1664
			}
1665
		}
1666

    
1667
		// Check if the gateway name is used in any enabled Static Route.
1668
		if (is_array($config['staticroutes']['route'])) {
1669
			foreach ($config['staticroutes']['route'] as $route) {
1670
				if ($route['gateway'] == $gateway_settings['name']) {
1671
					if (!isset($route['disabled'])) {
1672
						// There is a static route that uses this gateway and is enabled (not disabled).
1673
						$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']);
1674
					}
1675
				}
1676
			}
1677
		}
1678
	}
1679
	/* skip system gateways which have been automatically added */
1680
	if (($gateway_settings['gateway'] && (!is_ipaddr($gateway_settings['gateway'])) && ($gateway_settings['attribute'] !== "system")) && ($gateway_settings['gateway'] != "dynamic")) {
1681
		$input_errors[] = gettext("A valid gateway IP address must be specified.");
1682
	}
1683

    
1684
	if ($gateway_settings['gateway'] && is_ipaddr($gateway_settings['gateway'])) {
1685
		if (is_ipaddrv4($gateway_settings['gateway'])) {
1686
			if ($parent_ip == '') {
1687
				$parent_ip = get_interface_ip($gateway_settings['interface']);
1688
				$parent_sn = get_interface_subnet($gateway_settings['interface']);
1689
			}
1690
			if (empty($parent_ip) || empty($parent_sn)) {
1691
				$input_errors[] = gettext("Cannot add IPv4 Gateway Address because no IPv4 address could be found on the interface.");
1692
			} elseif (!isset($gateway_settings["nonlocalgateway"])) {
1693
				$subnets = array(gen_subnet($parent_ip, $parent_sn) . "/" . $parent_sn);
1694
				$vips = link_interface_to_vips($gateway_settings['interface']);
1695
				if (is_array($vips)) {
1696
					foreach ($vips as $vip) {
1697
						if (!is_ipaddrv4($vip['subnet'])) {
1698
							continue;
1699
						}
1700
						$subnets[] = gen_subnet($vip['subnet'], $vip['subnet_bits']) . "/" . $vip['subnet_bits'];
1701
					}
1702
				}
1703

    
1704
				$found = false;
1705
				foreach ($subnets as $subnet) {
1706
					if (ip_in_subnet($gateway_settings['gateway'], $subnet)) {
1707
						$found = true;
1708
						break;
1709
					}
1710
				}
1711

    
1712
				if ($found === false) {
1713
					$input_errors[] = sprintf(gettext("The gateway address %s does not lie within one of the chosen interface's subnets."), $gateway_settings['gateway']);
1714
				}
1715
			}
1716
		} else if (is_ipaddrv6($gateway_settings['gateway'])) {
1717
			/* do not do a subnet match on a link local address, it's valid */
1718
			if (!is_linklocal($gateway_settings['gateway'])) {
1719
				if ($parent_ip == '') {
1720
					$parent_ip = get_interface_ipv6($gateway_settings['interface']);
1721
					$parent_sn = get_interface_subnetv6($gateway_settings['interface']);
1722
				}
1723
				if (empty($parent_ip) || empty($parent_sn)) {
1724
					$input_errors[] = gettext("Cannot add IPv6 Gateway Address because no IPv6 address could be found on the interface.");
1725
				} elseif (!isset($gateway_settings["nonlocalgateway"])) {
1726
					$subnets = array(gen_subnetv6($parent_ip, $parent_sn) . "/" . $parent_sn);
1727
					$vips = link_interface_to_vips($gateway_settings['interface']);
1728
					if (is_array($vips)) {
1729
						foreach ($vips as $vip) {
1730
							if (!is_ipaddrv6($vip['subnet'])) {
1731
								continue;
1732
							}
1733
							$subnets[] = gen_subnetv6($vip['subnet'], $vip['subnet_bits']) . "/" . $vip['subnet_bits'];
1734
						}
1735
					}
1736

    
1737
					$found = false;
1738
					foreach ($subnets as $subnet) {
1739
						if (ip_in_subnet($gateway_settings['gateway'], $subnet)) {
1740
							$found = true;
1741
							break;
1742
						}
1743
					}
1744

    
1745
					if ($found === false) {
1746
						$input_errors[] = sprintf(gettext("The gateway address %s does not lie within one of the chosen interface's subnets."), $gateway_settings['gateway']);
1747
					}
1748
				}
1749
			}
1750
		}
1751

    
1752
		if (!empty($config['interfaces'][$gateway_settings['interface']]['ipaddr'])) {
1753
			if (is_ipaddr($config['interfaces'][$gateway_settings['interface']]['ipaddr']) && (empty($gateway_settings['gateway']) || $gateway_settings['gateway'] == "dynamic")) {
1754
				$input_errors[] = gettext("Dynamic gateway values cannot be specified for interfaces with a static IPv4 configuration.");
1755
			}
1756
		}
1757
		if (!empty($config['interfaces'][$gateway_settings['interface']]['ipaddrv6'])) {
1758
			if (is_ipaddr($config['interfaces'][$gateway_settings['interface']]['ipaddrv6']) && (empty($gateway_settings['gateway']) || $gateway_settings['gateway'] == "dynamic")) {
1759
				$input_errors[] = gettext("Dynamic gateway values cannot be specified for interfaces with a static IPv6 configuration.");
1760
			}
1761
		}
1762
	}
1763
	if (($gateway_settings['monitor'] != "") && ($gateway_settings['monitor'] != "dynamic")) {
1764
		validateipaddr($gateway_settings['monitor'], IPV4V6, "Monitor IP", $input_errors, false);
1765
	}
1766
	if (isset($gateway_settings['data_payload']) && is_numeric($gateway_settings['data_payload']) && $gateway_settings['data_payload'] < 0) {
1767
		$input_errors[] = gettext("A valid data payload must be specified.");
1768
	}
1769
	/* only allow correct IPv4 and IPv6 gateway addresses */
1770
	if (($gateway_settings['gateway'] <> "") && is_ipaddr($gateway_settings['gateway']) && $gateway_settings['gateway'] != "dynamic") {
1771
		if (is_ipaddrv6($gateway_settings['gateway']) && ($gateway_settings['ipprotocol'] == "inet")) {
1772
			$input_errors[] = sprintf(gettext("The IPv6 gateway address '%s' can not be used as a IPv4 gateway."), $gateway_settings['gateway']);
1773
		}
1774
		if (is_ipaddrv4($gateway_settings['gateway']) && ($gateway_settings['ipprotocol'] == "inet6")) {
1775
			$input_errors[] = sprintf(gettext("The IPv4 gateway address '%s' can not be used as a IPv6 gateway."), $gateway_settings['gateway']);
1776
		}
1777
	}
1778
	/* only allow correct IPv4 and IPv6 monitor addresses */
1779
	if (($gateway_settings['monitor'] <> "") && is_ipaddr($gateway_settings['monitor']) && $gateway_settings['monitor'] != "dynamic") {
1780
		if (is_ipaddrv6($gateway_settings['monitor']) && ($gateway_settings['ipprotocol'] == "inet")) {
1781
			$input_errors[] = sprintf(gettext("The IPv6 monitor address '%s' can not be used on a IPv4 gateway."), $gateway_settings['monitor']);
1782
		}
1783
		if (is_ipaddrv4($gateway_settings['monitor']) && ($gateway_settings['ipprotocol'] == "inet6")) {
1784
			$input_errors[] = sprintf(gettext("The IPv4 monitor address '%s' can not be used on a IPv6 gateway."), $gateway_settings['monitor']);
1785
		}
1786
	}
1787

    
1788
	if (isset($gateway_settings['name'])) {
1789
		/* check for overlaps */
1790
		foreach ($a_gateways as $gateway) {
1791
			if (isset($id) && ($a_gateways[$id]) && ($a_gateways[$id] === $gateway)) {
1792
				if ($gateway['name'] != $gateway_settings['name']) {
1793
					$input_errors[] = gettext("Changing name on a gateway is not allowed.");
1794
				}
1795
				continue;
1796
			}
1797
			if ($gateway_settings['name'] <> "") {
1798
				if (($gateway['name'] <> "") && ($gateway_settings['name'] == $gateway['name']) && ($gateway['attribute'] !== "system")) {
1799
					$input_errors[] = sprintf(gettext('The gateway name "%s" already exists.'), $gateway_settings['name']);
1800
					break;
1801
				}
1802
			}
1803
			if (is_ipaddr($gateway_settings['gateway'])) {
1804
				if (($gateway['gateway'] <> "") && ($gateway_settings['gateway'] == $gateway['gateway']) && ($gateway['attribute'] !== "system")) {
1805
					$input_errors[] = sprintf(gettext('The gateway IP address "%s" already exists.'), $gateway_settings['gateway']);
1806
					break;
1807
				}
1808
			}
1809
			if (is_ipaddr($gateway_settings['monitor'])) {
1810
				if (($gateway['monitor'] <> "") && ($gateway_settings['monitor'] == $gateway['monitor']) && ($gateway['attribute'] !== "system")) {
1811
					$input_errors[] = sprintf(gettext('The monitor IP address "%s" is already in use. A different monitor IP must be chosen.'), $gateway_settings['monitor']);
1812
					break;
1813
				}
1814
			}
1815
		}
1816
	}
1817

    
1818
	/* input validation of dpinger advanced parameters */
1819

    
1820
	$dpinger_default = return_dpinger_defaults();
1821
	$latencylow = $dpinger_default['latencylow'];
1822
	if ($gateway_settings['latencylow']) {
1823
		if (!is_numeric($gateway_settings['latencylow'])) {
1824
			$input_errors[] = gettext("The low latency threshold needs to be a numeric value.");
1825
		} else if ($gateway_settings['latencylow'] < 1) {
1826
			$input_errors[] = gettext("The low latency threshold needs to be positive.");
1827
		} else {
1828
			$latencylow = $gateway_settings['latencylow'];
1829
		}
1830
	}
1831

    
1832
	$latencyhigh = $dpinger_default['latencyhigh'];
1833
	if ($gateway_settings['latencyhigh']) {
1834
		if (!is_numeric($gateway_settings['latencyhigh'])) {
1835
			$input_errors[] = gettext("The high latency threshold needs to be a numeric value.");
1836
		} else if ($gateway_settings['latencyhigh'] < 1) {
1837
			$input_errors[] = gettext("The high latency threshold needs to be positive.");
1838
		} else {
1839
			$latencyhigh = $gateway_settings['latencyhigh'];
1840
		}
1841
	}
1842

    
1843
	$losslow = $dpinger_default['losslow'];
1844
	if ($gateway_settings['losslow']) {
1845
		if (!is_numeric($gateway_settings['losslow'])) {
1846
			$input_errors[] = gettext("The low Packet Loss threshold needs to be a numeric value.");
1847
		} else if ($gateway_settings['losslow'] < 1) {
1848
			$input_errors[] = gettext("The low Packet Loss threshold needs to be positive.");
1849
		} else if ($gateway_settings['losslow'] >= 100) {
1850
			$input_errors[] = gettext("The low Packet Loss threshold needs to be less than 100.");
1851
		} else {
1852
			$losslow = $gateway_settings['losslow'];
1853
		}
1854
	}
1855

    
1856
	$losshigh = $dpinger_default['losshigh'];
1857
	if ($gateway_settings['losshigh']) {
1858
		if (!is_numeric($gateway_settings['losshigh'])) {
1859
			$input_errors[] = gettext("The high Packet Loss threshold needs to be a numeric value.");
1860
		} else if ($gateway_settings['losshigh'] < 1) {
1861
			$input_errors[] = gettext("The high Packet Loss threshold needs to be positive.");
1862
		} else if ($gateway_settings['losshigh'] > 100) {
1863
			$input_errors[] = gettext("The high Packet Loss threshold needs to be 100 or less.");
1864
		} else {
1865
			$losshigh = $gateway_settings['losshigh'];
1866
		}
1867
	}
1868

    
1869
	$time_period = $dpinger_default['time_period'];
1870
	if ($gateway_settings['time_period']) {
1871
		if (!is_numeric($gateway_settings['time_period'])) {
1872
			$input_errors[] = gettext("The time period over which results are averaged needs to be a numeric value.");
1873
		} else if ($gateway_settings['time_period'] < 1) {
1874
			$input_errors[] = gettext("The time period over which results are averaged needs to be positive.");
1875
		} else {
1876
			$time_period = $gateway_settings['time_period'];
1877
		}
1878
	}
1879

    
1880
	$interval = $dpinger_default['interval'];
1881
	if ($gateway_settings['interval']) {
1882
		if (!is_numeric($gateway_settings['interval'])) {
1883
			$input_errors[] = gettext("The probe interval needs to be a numeric value.");
1884
		} else if ($gateway_settings['interval'] < 1) {
1885
			$input_errors[] = gettext("The probe interval needs to be positive.");
1886
		} else {
1887
			$interval = $gateway_settings['interval'];
1888
		}
1889
	}
1890

    
1891
	$loss_interval = $dpinger_default['loss_interval'];
1892
	if ($gateway_settings['loss_interval']) {
1893
		if (!is_numeric($gateway_settings['loss_interval'])) {
1894
			$input_errors[] = gettext("The loss interval needs to be a numeric value.");
1895
		} else if ($gateway_settings['loss_interval'] < 1) {
1896
			$input_errors[] = gettext("The loss interval setting needs to be positive.");
1897
		} else {
1898
			$loss_interval = $gateway_settings['loss_interval'];
1899
		}
1900
	}
1901

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

    
1913
	if ($latencylow >= $latencyhigh) {
1914
		$input_errors[] = gettext(
1915
		    "The high latency threshold needs to be greater than the low latency threshold");
1916
	}
1917

    
1918
	if ($losslow >= $losshigh) {
1919
		$input_errors[] = gettext(
1920
		    "The high packet loss threshold needs to be higher than the low packet loss threshold");
1921
	}
1922

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

    
1929
	// Ensure that the time period is greater than 2 times the probe interval plus the loss interval.
1930
	if (($interval * 2 + $loss_interval) >= $time_period) {
1931
		$input_errors[] = gettext("The time period needs to be greater than twice the probe interval plus the loss interval.");
1932
	}
1933

    
1934
	// There is no point recalculating the average latency and loss more often than the probe interval.
1935
	// So the alert interval needs to be >= probe interval.
1936
	if ($interval > $alert_interval) {
1937
		$input_errors[] = gettext("The alert interval needs to be greater than or equal to the probe interval.");
1938
	}
1939

    
1940
	return $input_errors;
1941
}
1942

    
1943
// Save gateway settings.
1944
// $gateway_settings - the array of gateway setting parameters
1945
// $realid - the index of the gateway to be modified (otherwise "" if adding a new gateway)
1946

    
1947
// This function is responsible to:
1948
//   Setup the gateway parameter structure from the gateway settings input parameter
1949
//   Save the structure into the config
1950
//   Remove any run-time settings from gateway parameters that are changed (e.g. remove routes to addresses that are changing)
1951

    
1952
// A subsequent "apply" step will implement the added/changed gateway.
1953

    
1954
function save_gateway($gateway_settings, $realid = "") {
1955
	global $config;
1956

    
1957
	$a_gateway_item = &$config['gateways']['gateway_item'];
1958
	$reloadif = "";
1959
	$gateway = array();
1960

    
1961
	if (empty($gateway_settings['interface'])) {
1962
		$gateway['interface'] = $gateway_settings['friendlyiface'];
1963
	} else {
1964
		$gateway['interface'] = $gateway_settings['interface'];
1965
	}
1966
	if (is_ipaddr($gateway_settings['gateway'])) {
1967
		$gateway['gateway'] = $gateway_settings['gateway'];
1968
	} else {
1969
		$gateway['gateway'] = "dynamic";
1970
	}
1971
	$gateway['name'] = $gateway_settings['name'];
1972
	$gateway['weight'] = $gateway_settings['weight'];
1973
	$gateway['ipprotocol'] = $gateway_settings['ipprotocol'];
1974
	if ($gateway_settings['interval']) {
1975
		$gateway['interval'] = $gateway_settings['interval'];
1976
	}
1977

    
1978
	if ($gateway_settings['time_period']) {
1979
		$gateway['time_period'] = $gateway_settings['time_period'];
1980
	}
1981
	if ($gateway_settings['alert_interval']) {
1982
		$gateway['alert_interval'] = $gateway_settings['alert_interval'];
1983
	}
1984

    
1985
	$gateway['descr'] = $gateway_settings['descr'];
1986
	if ($gateway_settings['monitor_disable'] == "yes") {
1987
		$gateway['monitor_disable'] = true;
1988
	}
1989
	if ($gateway_settings['action_disable'] == "yes") {
1990
		$gateway['action_disable'] = true;
1991
	}
1992
	if ($gateway_settings['nonlocalgateway'] == "yes") {
1993
		$gateway['nonlocalgateway'] = true;
1994
	}
1995
	if ($gateway_settings['force_down'] == "yes") {
1996
		$gateway['force_down'] = true;
1997
	}
1998
	if (is_ipaddr($gateway_settings['monitor'])) {
1999
		$gateway['monitor'] = $gateway_settings['monitor'];
2000
	}
2001
	if (isset($gateway_settings['data_payload']) && $gateway_settings['data_payload'] > 0) {
2002
		$gateway['data_payload'] = $gateway_settings['data_payload'];
2003
	}
2004

    
2005
	/* NOTE: If gateway ip is changed need to cleanup the old static interface route */
2006
	if ($gateway_settings['monitor'] != "dynamic" && !empty($a_gateway_item[$realid]) && is_ipaddr($a_gateway_item[$realid]['gateway']) &&
2007
		$gateway['gateway'] != $a_gateway_item[$realid]['gateway'] &&
2008
		isset($a_gateway_item[$realid]["nonlocalgateway"])) {
2009
		$realif = get_real_interface($a_gateway_item[$realid]['interface']);
2010
		$inet = (!is_ipaddrv4($a_gateway_item[$realid]['gateway']) ? "-inet6" : "-inet");
2011
		$cmd = "/sbin/route delete $inet " . escapeshellarg($a_gateway_item[$realid]['gateway']) . " -iface " . escapeshellarg($realif);
2012
		mwexec($cmd);
2013
	}
2014

    
2015
	/* NOTE: If monitor ip is changed need to cleanup the old static route */
2016
	if ($gateway_settings['monitor'] != "dynamic" && !empty($a_gateway_item[$realid]) && is_ipaddr($a_gateway_item[$realid]['monitor']) &&
2017
		$gateway_settings['monitor'] != $a_gateway_item[$realid]['monitor'] && $gateway['gateway'] != $a_gateway_item[$realid]['monitor']) {
2018
		if (is_ipaddrv4($a_gateway_item[$realid]['monitor'])) {
2019
			mwexec("/sbin/route delete " . escapeshellarg($a_gateway_item[$realid]['monitor']));
2020
		} else {
2021
			mwexec("/sbin/route delete -inet6 " . escapeshellarg($a_gateway_item[$realid]['monitor']));
2022
		}
2023
	}
2024

    
2025
	if ($gateway_settings['defaultgw'] == "yes" || $gateway_settings['defaultgw'] == "on") {
2026
		// a new default gateway is being saved.
2027
		$i = 0;
2028
		/* remove the default gateway bits for all gateways with the same address family */
2029
		if (is_array($a_gateway_item)) {
2030
			foreach ($a_gateway_item as $gw) {
2031
				if ($gateway['ipprotocol'] == $gw['ipprotocol']) {
2032
					if ($gw['interface'] != $gateway_settings['interface'] &&
2033
						($gw['name'] == $config['gateways']['defaultgw4'] || $gw['name'] == $config['gateways']['defaultgw6'])) {
2034
						// remember the old default gateway interface to call with a "interface reconfigure" event.
2035
						$reloadif = $gw['interface'];
2036
					}
2037
				}
2038
				$i++;
2039
			}
2040
		}
2041
		if ($gateway['ipprotocol'] == "inet") {
2042
			$config['gateways']['defaultgw4'] = $gateway['name'];
2043
		} elseif ($gateway['ipprotocol'] == "inet6") {
2044
			$config['gateways']['defaultgw6'] = $gateway['name'];
2045
		}
2046
	}
2047

    
2048
	if ($gateway_settings['latencylow']) {
2049
		$gateway['latencylow'] = $gateway_settings['latencylow'];
2050
	}
2051
	if ($gateway_settings['latencyhigh']) {
2052
		$gateway['latencyhigh'] = $gateway_settings['latencyhigh'];
2053
	}
2054
	if ($gateway_settings['losslow']) {
2055
		$gateway['losslow'] = $gateway_settings['losslow'];
2056
	}
2057
	if ($gateway_settings['losshigh']) {
2058
		$gateway['losshigh'] = $gateway_settings['losshigh'];
2059
	}
2060
	if ($gateway_settings['loss_interval']) {
2061
		$gateway['loss_interval'] = $gateway_settings['loss_interval'];
2062
	}
2063
	/* when saving the manual gateway we use the attribute which has the corresponding id */
2064
	if (isset($realid) && $a_gateway_item[$realid]) {
2065
		$preserve_disabled = isset($a_gateway_item[$realid]['disabled']);
2066
		$a_gateway_item[$realid] = $gateway;
2067
		if ($preserve_disabled) {
2068
			$a_gateway_item[$realid]['disabled'] = true;
2069
		}
2070
	} else {
2071
		$a_gateway_item[] = $gateway;
2072
	}
2073
	gateway_set_enabled($gateway_settings['name'], !isset($gateway_settings['disabled']));
2074

    
2075
	mark_subsystem_dirty('staticroutes');
2076

    
2077
	write_config();
2078

    
2079
	if (!empty($reloadif)) {
2080
		send_event("interface reconfigure {$reloadif}");
2081
	}
2082
}
2083

    
2084
function gateway_set_enabled($name, $enabled) {
2085
	global $config;
2086
	if (is_array($config['gateways']['gateway_item'])) {
2087
		foreach($config['gateways']['gateway_item'] as &$item) {
2088
			if ($item['name'] == $name) {
2089
				$gateway = &$item;
2090
			}
2091
		}
2092
	}
2093
	if (!isset($gateway)) {
2094
		return;
2095
	}
2096
	if ($enabled) {
2097
		unset($gateway['disabled']);
2098
	} else {
2099
		/* Check if the gateway was enabled but changed to disabled. */
2100
		if (!isset($gateway['disabled'])) {
2101
			/*  If the disabled gateway was the default route, remove the default route */
2102
			if (is_ipaddr($gateway['gateway'])) {
2103
				$inet = (!is_ipaddrv4($gateway['gateway']) ? 'inet6' : 'inet');
2104
				if ($inet == 'inet') {
2105
					$cgw = getcurrentdefaultgatewayip('inet');
2106
				} else {
2107
					$cgw = getcurrentdefaultgatewayip('inet6');
2108
				}
2109
				if ($gateway['gateway'] == $cgw) {
2110
					mwexec("/sbin/route delete -{$inet} default");
2111
				}
2112
			}
2113
			$gateway['disabled'] = true;
2114
		}
2115
	}
2116
}
2117

    
2118
function gateway_or_gwgroup_exists($name) {
2119
	global $config;
2120
	if (is_array($config['gateways']['gateway_item'])) {
2121
		foreach($config['gateways']['gateway_item'] as $item) {
2122
			if ($item['name'] == $name) {
2123
				return true;
2124
			}
2125
		}
2126
	}
2127
	if (is_array($config['gateways']['gateway_group'])) {
2128
		foreach($config['gateways']['gateway_group'] as $item) {
2129
			if ($item['name'] == $name) {
2130
				return true;
2131
			}
2132
		}
2133
	}
2134
	return false;
2135
}
2136

    
2137
?>
(21-21/60)