Project

General

Profile

Download (17.3 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * vslb.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2005-2008 Bill Marquette
7
 * Copyright (c) 2004-2016 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
/* include all configuration functions */
24

    
25
class Monitor {
26
	private $conf = array();
27
	function __construct($config) {
28
		$this->conf = $config;
29
	}
30

    
31
	public function p() {
32
		return "check {$this->get('proto')}";
33
	}
34
	private function get($var) {
35
		return isset($this->$var) ? $this->$var : "";
36
	}
37
	protected function config($element) {
38
		return isset($this->conf[$element]) ? $this->conf[$element] : "";
39
	}
40
}
41

    
42
class TCPMonitor extends Monitor {
43
	protected $proto = 'tcp';
44
}
45

    
46
class SSLMonitor extends Monitor {
47
	protected $proto = 'ssl';
48
}
49

    
50
class ICMPMonitor extends Monitor {
51
	protected $proto = 'icmp';
52
}
53

    
54
class HTTPMonitor extends Monitor {
55
	protected $proto = 'http';
56
	function __construct($config) {
57
		parent::__construct($config);
58
	}
59
	public function p() {
60
		$method = ($this->code() != "") ? $this->code() : $this->digest();
61
		return "check {$this->proto} {$this->path()} {$this->host()} {$method}";
62
	}
63

    
64
	private function path() {
65
		return $this->config('path') != "" ? "'{$this->config('path')}'" : "";
66
	}
67

    
68
	private function host() {
69
		return $this->config('host') != "" ? "host {$this->config('host')}" : "";
70
	}
71

    
72
	private function code() {
73
		return $this->config('code') != "" ? "code {$this->config('code')}" : "";
74
	}
75

    
76
	private function digest() {
77
		return $this->config('digest') != "" ? "digest {$this->config('digest')}" : "";
78
	}
79
}
80

    
81
class HTTPSMonitor extends HTTPMonitor {
82
	protected $proto = 'https';
83
}
84

    
85
class SendMonitor extends Monitor {
86
	private $proto = 'send';
87
	function __construct($config) {
88
		parent::__construct($config);
89
	}
90
	public function p() {
91
		return "check {$this->proto} {$this->data()} expect {$this->pattern()} {$this->ssl()}";
92
	}
93

    
94

    
95
	private function data() {
96
		return $this->config('send') != "" ? "\"{$this->config('send')}\"" : "\"\"";
97
	}
98

    
99
	private function pattern() {
100
		return $this->config('expect') != "" ? "\"{$this->config('expect')}\"" : "\"\"";
101
	}
102

    
103
	private function ssl() {
104
		return $this->config('ssl') == true ? "ssl" : "";
105
	}
106
}
107

    
108
function echo_lbaction($action) {
109
	global $config;
110

    
111
	// Index actions by name
112
	$actions_a = array();
113
	for ($i = 0; isset($config['load_balancer']['lbaction'][$i]); $i++) {
114
		$actions_a[$config['load_balancer']['lbaction'][$i]['name']] = $config['load_balancer']['lbaction'][$i];
115
	}
116

    
117
	$ret = "";
118
	$ret .= "{$actions_a[$action]['direction']} {$actions_a[$action]['type']} {$actions_a[$action]['action']}";
119
	switch ($actions_a[$action]['action']) {
120
		case 'append':
121
			$ret .= " \"{$actions_a[$action]['options']['value']}\" to \"{$actions_a[$action]['options']['akey']}\"";
122
			break;
123
		case 'change':
124
			$ret .= " \"{$actions_a[$action]['options']['akey']}\" to \"{$actions_a[$action]['options']['value']}\"";
125
			break;
126
		case 'expect':
127
			$ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\"";
128
			break;
129
		case 'filter':
130
			$ret .= " \"{$actions_a[$action]['options']['value']}\" from \"{$actions_a[$action]['options']['akey']}\"";
131
			break;
132
		case 'hash':
133
			$ret .= " \"{$actions_a[$action]['options']['akey']}\"";
134
			break;
135
		case 'log':
136
			$ret .= " \"{$actions_a[$action]['options']['akey']}\"";
137
			break;
138
	}
139
	return $ret;
140
}
141

    
142
function relayd_configure($kill_first=false) {
143
	global $config, $g;
144

    
145
	// have to do this until every call to filter.inc is
146
	// require_once() instead of require().
147
	if (!function_exists('filter_expand_alias_array')) {
148
		require_once("filter.inc");
149
	}
150

    
151
	$vs_a = $config['load_balancer']['virtual_server'];
152
	$pool_a = $config['load_balancer']['lbpool'];
153
	$protocol_a = $config['load_balancer']['lbprotocol'];
154
	$setting = $config['load_balancer']['setting'];
155

    
156
	$check_a = array();
157

    
158
	foreach ((array)$config['load_balancer']['monitor_type'] as $type) {
159
		switch ($type['type']) {
160
			case 'icmp':
161
				$mon = new ICMPMonitor($type['options']);
162
				break;
163
			case 'tcp':
164
				$mon = new TCPMonitor($type['options']);
165
				break;
166
			case 'http':
167
				$mon = new HTTPMonitor($type['options']);
168
				break;
169
			case 'https':
170
				$mon = new HTTPSMonitor($type['options']);
171
				break;
172
			case 'send':
173
				$mon = new SendMonitor($type['options']);
174
				break;
175
		}
176
		if ($mon) {
177
			$check_a[$type['name']] = $mon->p();
178
		}
179
	}
180

    
181

    
182
	$fd = fopen("{$g['varetc_path']}/relayd.conf", "w");
183
	$conf .= "log updates \n";
184

    
185
	/* Global timeout, interval and prefork settings
186
	   if not specified by the user:
187
	   - use a 1000 ms timeout value as in pfsense 2.0.1 and above
188
	   - leave interval and prefork empty, relayd will use its default values */
189

    
190
	if (isset($setting['timeout']) && !empty($setting['timeout'])) {
191
		$conf .= "timeout ".$setting['timeout']." \n";
192
	} else {
193
		$conf .= "timeout 1000 \n";
194
	}
195

    
196
	if (isset($setting['interval']) && !empty($setting['interval'])) {
197
		$conf .= "interval ".$setting['interval']." \n";
198
	}
199

    
200
	if (isset($setting['prefork']) && !empty($setting['prefork'])) {
201
		$conf .= "prefork ".$setting['prefork']." \n";
202
	}
203

    
204
	/* reindex pools by name as we loop through the pools array */
205
	$pools = array();
206
	/* Virtual server pools */
207
	if (is_array($pool_a)) {
208
		for ($i = 0; isset($pool_a[$i]); $i++) {
209
			if (is_array($pool_a[$i]['servers'])) {
210
				if (!empty($pool_a[$i]['retry'])) {
211
					$retrytext = " retry {$pool_a[$i]['retry']}";
212
				} else {
213
					$retrytext = "";
214
				}
215
				$conf .= "table <{$pool_a[$i]['name']}> {\n";
216
				foreach ($pool_a[$i]['servers'] as $server) {
217
					if (is_subnetv4($server)) {
218
						foreach (subnetv4_expand($server) as $ip) {
219
							$conf .= "\t{$ip}{$retrytext}\n";
220
						}
221
					} else {
222
						$conf .= "\t{$server}{$retrytext}\n";
223
					}
224
				}
225
				$conf .= "}\n";
226
				/* Index by name for easier fetching when we loop through the virtual servers */
227
				$pools[$pool_a[$i]['name']] = $pool_a[$i];
228
			}
229
		}
230
	}
231
//  if (is_array($protocol_a)) {
232
//    for ($i = 0; isset($protocol_a[$i]); $i++) {
233
//      $proto = "{$protocol_a[$i]['type']} protocol \"{$protocol_a[$i]['name']}\" {\n";
234
//      if (is_array($protocol_a[$i]['lbaction'])) {
235
//        if ($protocol_a[$i]['lbaction'][0] == "") {
236
//          continue;
237
//        }
238
//        for ($a = 0; isset($protocol_a[$i]['lbaction'][$a]); $a++) {
239
//          $proto .= "  " . echo_lbaction($protocol_a[$i]['lbaction'][$a]) . "\n";
240
//        }
241
//      }
242
//      $proto .= "}\n";
243
//      $conf .= $proto;
244
//    }
245
//  }
246

    
247
	$conf .= "dns protocol \"dnsproto\" {\n";
248
	$conf .= "\t" . "tcp { nodelay, sack, socket buffer 1024, backlog 1000 }\n";
249
	$conf .= "}\n";
250

    
251
	if (is_array($vs_a)) {
252
		for ($i = 0; isset($vs_a[$i]); $i++) {
253

    
254
			$append_port_to_name = false;
255
			if (is_alias($pools[$vs_a[$i]['poolname']]['port'])) {
256
				$dest_port_array = filter_expand_alias_array($pools[$vs_a[$i]['poolname']]['port']);
257
				$append_port_to_name = true;
258
			} else {
259
				$dest_port_array = array($pools[$vs_a[$i]['poolname']]['port']);
260
			}
261
			if (is_alias($vs_a[$i]['port'])) {
262
				$src_port_array = filter_expand_alias_array($vs_a[$i]['port']);
263
				$append_port_to_name = true;
264
			} else if ($vs_a[$i]['port']) {
265
				$src_port_array = array($vs_a[$i]['port']);
266
			} else {
267
				$src_port_array = $dest_port_array;
268
			}
269

    
270
			$append_ip_to_name = false;
271
			if (is_alias($vs_a[$i]['ipaddr'])) {
272
				$ip_list = array();
273
				foreach (filter_expand_alias_array($vs_a[$i]['ipaddr']) as $item) {
274
					log_error("item is $item");
275
					if (is_subnetv4($item)) {
276
						$ip_list = array_merge($ip_list, subnetv4_expand($item));
277
					} else {
278
						$ip_list[] = $item;
279
					}
280
				}
281
				$append_ip_to_name = true;
282
			} else if (is_subnetv4($vs_a[$i]['ipaddr'])) {
283
				$ip_list = subnetv4_expand($vs_a[$i]['ipaddr']);
284
				$append_ip_to_name = true;
285
			} else {
286
				$ip_list = array($vs_a[$i]['ipaddr']);
287
			}
288

    
289
			for ($j = 0; $j < count($ip_list); $j += 1) {
290
				$ip = $ip_list[$j];
291
				for ($k = 0; $k < count($src_port_array) && $k < count($dest_port_array); $k += 1) {
292
					$src_port = $src_port_array[$k];
293
					$dest_port = $dest_port_array[$k];
294
					if (is_portrange($dest_port)) {
295
						$dest_ports = explode(':', $dest_port);
296
						$dest_port = $dest_ports[0];
297
					}
298

    
299
					$name = $vs_a[$i]['name'];
300
					if ($append_ip_to_name) {
301
						$name .= "_" . $j;
302
					}
303
					if ($append_port_to_name) {
304
						$name .= "_" . str_replace(":", "_", $src_port);
305
					}
306

    
307
					if (($vs_a[$i]['mode'] == 'relay') || ($vs_a[$i]['relay_protocol'] == 'dns')) {
308
						$conf .= "relay \"{$name}\" {\n";
309
						$conf .= "  listen on {$ip} port {$src_port}\n";
310

    
311
						if ($vs_a[$i]['relay_protocol'] == "dns") {
312
							$conf .= "  protocol \"dnsproto\"\n";
313
						} else {
314
							$conf .= "  protocol \"{$vs_a[$i]['relay_protocol']}\"\n";
315
						}
316
						$lbmode = "";
317
						if ($pools[$vs_a[$i]['poolname']]['mode'] == "loadbalance") {
318
							$lbmode = "mode loadbalance";
319
						}
320

    
321
						$conf .= "  forward to <{$vs_a[$i]['poolname']}> port {$dest_port} {$lbmode} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n";
322

    
323
						if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) {
324
							$conf .= "  forward to <{$vs_a[$i]['sitedown']}> port {$dest_port} {$lbmode} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n";
325
						}
326
						$conf .= "}\n";
327
					} else {
328
						$conf .= "redirect \"{$name}\" {\n";
329
						$conf .= "  listen on {$ip} port {$src_port}\n";
330
						$conf .= "  forward to <{$vs_a[$i]['poolname']}> port {$dest_port} {$check_a[$pools[$vs_a[$i]['poolname']]['monitor']]} \n";
331

    
332
						if (isset($config['system']['lb_use_sticky'])) {
333
							$conf .= "  sticky-address\n";
334
						}
335

    
336
						/* sitedown MUST use the same port as the primary pool - sucks, but it's a relayd thing */
337
						if (isset($vs_a[$i]['sitedown']) && strlen($vs_a[$i]['sitedown']) > 0 && ($vs_a[$i]['relay_protocol'] != 'dns')) {
338
							$conf .= "  forward to <{$vs_a[$i]['sitedown']}> port {$dest_port} {$check_a[$pools[$vs_a[$i]['sitedown']]['monitor']]} \n";
339
						}
340

    
341
						$conf .= "}\n";
342
					}
343
				}
344
			}
345
		}
346
	}
347
	fwrite($fd, $conf);
348
	fclose($fd);
349

    
350
	if (is_process_running('relayd')) {
351
		if (!empty($vs_a)) {
352
			if ($kill_first) {
353
				mwexec('pkill relayd');
354
				/* Remove all active relayd anchors now that relayd is no longer running. */
355
				cleanup_lb_anchor("*");
356
				mwexec("/usr/local/sbin/relayd -f {$g['varetc_path']}/relayd.conf");
357
			} else {
358
				// it's running and there is a config, just reload
359
				mwexec("/usr/local/sbin/relayctl reload");
360
			}
361
		} else {
362
			/*
363
			 * XXX: Something breaks our control connection with relayd
364
			 * and makes 'relayctl stop' not work
365
			 * rule reloads are the current suspect
366
			 * mwexec('/usr/local/sbin/relayctl stop');
367
			 *  returns "command failed"
368
			 */
369
			mwexec('pkill relayd');
370
			/* Remove all active relayd anchors now that relayd is no longer running. */
371
			cleanup_lb_anchor("*");
372
		}
373
	} else {
374
		if (!empty($vs_a)) {
375
			// not running and there is a config, start it
376
			/* Remove all active relayd anchors so it can start fresh. */
377
			cleanup_lb_anchor("*");
378
			mwexec("/usr/local/sbin/relayd -f {$g['varetc_path']}/relayd.conf");
379
		}
380
	}
381
}
382

    
383
function get_lb_redirects() {
384
/*
385
# relayctl show summary
386
Id   Type      Name                      Avlblty Status
387
1    redirect  testvs2                           active
388
5    table     test2:80                          active (3 hosts up)
389
11   host      192.168.1.2               91.55%  up
390
10   host      192.168.1.3               100.00% up
391
9    host      192.168.1.4               88.73%  up
392
3    table     test:80                           active (1 hosts up)
393
7    host      192.168.1.2               66.20%  down
394
6    host      192.168.1.3               97.18%  up
395
0    redirect  testvs                            active
396
3    table     test:80                           active (1 hosts up)
397
7    host      192.168.1.2               66.20%  down
398
6    host      192.168.1.3               97.18%  up
399
4    table     testvs-sitedown:80                active (1 hosts up)
400
8    host      192.168.1.4               84.51%  up
401
# relayctl show redirects
402
Id   Type      Name                      Avlblty Status
403
1    redirect  testvs2                           active
404
0    redirect  testvs                            active
405
# relayctl show redirects
406
Id   Type      Name                      Avlblty Status
407
1    redirect  testvs2                           active
408
		   total: 2 sessions
409
		   last: 2/60s 2/h 2/d sessions
410
		   average: 1/60s 0/h 0/d sessions
411
0    redirect  testvs                            active
412
*/
413
	$rdr_a = array();
414
	exec('/usr/local/sbin/relayctl show redirects 2>&1', $rdr_a);
415
	$relay_a = array();
416
	exec('/usr/local/sbin/relayctl show relays 2>&1', $relay_a);
417
	$vs = array();
418
	$cur_entry = "";
419
	for ($i = 0; isset($rdr_a[$i]); $i++) {
420
		$line = $rdr_a[$i];
421
		if (preg_match("/^[0-9]+/", $line)) {
422
			$regs = array();
423
			if ($x = preg_match("/^[0-9]+\s+redirect\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) {
424
				$cur_entry = trim($regs[1]);
425
				$vs[trim($regs[1])] = array();
426
				$vs[trim($regs[1])]['status'] = trim($regs[2]);
427
			}
428
		} elseif (($x = preg_match("/^\s+total:\s(.*)\ssessions/", $line, $regs)) && !empty($cur_entry)) {
429
			$vs[$cur_entry]['total'] = trim($regs[1]);
430
		} elseif (($x = preg_match("/^\s+last:\s(.*)\ssessions/", $line, $regs)) && !empty($cur_entry)) {
431
			$vs[$cur_entry]['last'] = trim($regs[1]);
432
		} elseif (($x = preg_match("/^\s+average:(.*)\ssessions/", $line, $regs)) && !empty($cur_entry)) {
433
			$vs[$cur_entry]['average'] = trim($regs[1]);
434
		}
435
	}
436
	$cur_entry = "";
437
	for ($i = 0; isset($relay_a[$i]); $i++) {
438
		$line = $relay_a[$i];
439
		if (preg_match("/^[0-9]+/", $line)) {
440
			$regs = array();
441
			if ($x = preg_match("/^[0-9]+\s+relay\s+([^\s]+)\s+([^\s]+)/", $line, $regs)) {
442
				$cur_entry = trim($regs[1]);
443
				$vs[trim($regs[1])] = array();
444
				$vs[trim($regs[1])]['status'] = trim($regs[2]);
445
			}
446
		} elseif (($x = preg_match("/^\s+total:\s(.*)\ssessions/", $line, $regs)) && !empty($cur_entry)) {
447
			$vs[$cur_entry]['total'] = trim($regs[1]);
448
		} elseif (($x = preg_match("/^\s+last:\s(.*)\ssessions/", $line, $regs)) && !empty($cur_entry)) {
449
			$vs[$cur_entry]['last'] = trim($regs[1]);
450
		} elseif (($x = preg_match("/^\s+average:(.*)\ssessions/", $line, $regs)) && !empty($cur_entry)) {
451
			$vs[$cur_entry]['average'] = trim($regs[1]);
452
		}
453
	}
454
	return $vs;
455
}
456

    
457
function get_lb_summary() {
458
	$relayctl = array();
459
	exec('/usr/local/sbin/relayctl show summary 2>&1', $relayctl);
460
	$relay_hosts=Array();
461
	foreach ((array) $relayctl as $line) {
462
		$t = explode("\t", $line);
463
		switch (trim($t[1])) {
464
			case "table":
465
				$curpool=trim($t[2]);
466
				break;
467
			case "host":
468
				$curhost=trim($t[2]);
469
				$relay_hosts[$curpool][$curhost]['avail']=trim($t[3]);
470
				$relay_hosts[$curpool][$curhost]['state']=trim($t[4]);
471
				break;
472
		}
473
	}
474
	return $relay_hosts;
475
}
476

    
477
/* Get a list of all relayd virtual server anchors */
478
function get_lb_anchors() {
479
	/* NOTE: These names come back prepended with "relayd/" e.g. "relayd/MyVSName" */
480
	return explode("\n", trim(`/sbin/pfctl -sA -a relayd | /usr/bin/awk '{print $1;}'`));
481
}
482

    
483
/* Remove NAT rules from a relayd anchor that is no longer in use.
484
	$anchorname can either be * to clear all anchors or a specific anchor name.*/
485
function cleanup_lb_anchor($anchorname = "*") {
486
	$lbanchors = get_lb_anchors();
487
	foreach ($lbanchors as $lba) {
488
		if (($anchorname == "*") || ($lba == "relayd/{$anchorname}")) {
489
			/* Flush both the NAT and the Table for the anchor, so it will be completely removed by pf. */
490
			mwexec("/sbin/pfctl -a " . escapeshellarg($lba) . " -F nat");
491
			mwexec("/sbin/pfctl -a " . escapeshellarg($lba) . " -F Tables");
492
		}
493
	}
494
}
495

    
496
/* Mark an anchor for later cleanup. This will allow us to remove an old VS name */
497
function cleanup_lb_mark_anchor($name) {
498
	global $g;
499
	/* Nothing to do! */
500
	if (empty($name)) {
501
		return;
502
	}
503
	$filename = "{$g['tmp_path']}/relayd_anchors_remove";
504
	$cleanup_anchors = array();
505
	/* Read in any currently unapplied name changes */
506
	if (file_exists($filename)) {
507
		$cleanup_anchors = explode("\n", file_get_contents($filename));
508
	}
509
	/* Only add the anchor to the list if it's not already there. */
510
	if (!in_array($name, $cleanup_anchors)) {
511
		$cleanup_anchors[] = $name;
512
	}
513
	file_put_contents($filename, implode("\n", $cleanup_anchors));
514
}
515

    
516
/* Cleanup relayd anchors that have been marked for cleanup. */
517
function cleanup_lb_marked() {
518
	global $g, $config;
519
	$filename = "{$g['tmp_path']}/relayd_anchors_remove";
520
	$cleanup_anchors = array();
521
	/* Nothing to do! */
522
	if (!file_exists($filename)) {
523
		return;
524
	} else {
525
		$cleanup_anchors = explode("\n", file_get_contents($filename));
526
		/* Nothing to do! */
527
		if (empty($cleanup_anchors)) {
528
			return;
529
		}
530
	}
531

    
532
	/* Load current names so we can make sure we don't remove an anchor that is still in use. */
533
	$vs_a = $config['load_balancer']['virtual_server'];
534
	$active_vsnames = array();
535
	if (is_array($vs_a)) {
536
		foreach ($vs_a as $vs) {
537
			$active_vsnames[] = $vs['name'];
538
		}
539
	}
540

    
541
	foreach ($cleanup_anchors as $anchor) {
542
		/* Only cleanup an anchor if it is not still active. */
543
		if (!in_array($anchor, $active_vsnames)) {
544
			cleanup_lb_anchor($anchor);
545
		}
546
	}
547
	unlink_if_exists($filename);
548
}
549

    
550
?>
(46-46/51)