Project

General

Profile

Download (69.4 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
	$gateways_arr = return_gateways_array();
1375
	foreach ($gateways_arr as $gw) {
1376
		if ($gw['name'] == $gwname) {
1377
			$gw['type'] = 'gateway';
1378
			return $gw;
1379
		}
1380
	}
1381

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

    
1391
	return false;
1392
}
1393

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

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

    
1403
	return false;
1404
}
1405

    
1406
function lookup_gateway_monitor_ip_by_name($name) {
1407

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

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

    
1418
	return (false);
1419
}
1420

    
1421
function lookup_gateway_interface_by_name($name) {
1422

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

    
1429
	return (false);
1430
}
1431

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

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

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

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

    
1464
	}
1465

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

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

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

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

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

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

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

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

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

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

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

    
1561
	return false;
1562
}
1563

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

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

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

    
1590
	return false;
1591
}
1592

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1939
	return $input_errors;
1940
}
1941

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

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

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

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

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

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

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

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

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

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

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

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

    
2074
	mark_subsystem_dirty('staticroutes');
2075

    
2076
	write_config();
2077

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

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

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

    
2136
?>
(22-22/60)