Project

General

Profile

Download (34.4 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
	guiconfig.inc
4
	by Scott Ullrich, Copyright 2004, All rights reserved.
5
	originally based on of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

    
20
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31
/*
32
	pfSense_MODULE:	base
33
*/
34

    
35
/* Include authentication routines */
36
/* THIS MUST BE ABOVE ALL OTHER CODE */
37
if(!$nocsrf) {
38
	function csrf_startup() {
39
		csrf_conf('rewrite-js', '/csrf/csrf-magic.js');
40
		$timeout_minutes = isset($config['system']['webgui']['session_timeout']) ?  $config['system']['webgui']['session_timeout'] : 240;
41
		csrf_conf('expires', $timeout_minutes * 60);
42
	}
43
	require_once("csrf/csrf-magic.php");
44
}
45

    
46
/* make sure nothing is cached */
47
if (!$omit_nocacheheaders) {
48
	header("Expires: 0");
49
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
50
	header("Cache-Control: no-cache, no-store, must-revalidate");
51
	header("Pragma: no-cache");
52
}
53

    
54
header("X-Frame-Options: SAMEORIGIN");
55
require_once("authgui.inc");
56

    
57
/* parse the configuration and include all configuration functions */
58
require_once("functions.inc");
59

    
60
/* Pull in all the gui related display classes) */
61
foreach (scandir("/usr/local/www/classes/") as $file) {
62
	if (substr($file, -4) == ".inc") {
63
		require_once("classes/{$file}");
64
	}
65
}
66

    
67
$g['theme'] = get_current_theme();
68

    
69
/* Set the default interface language */
70
if($config['system']['language'] <> "") {
71
	$g['language'] = $config['system']['language'];
72
} elseif ($g['language'] == "") {
73
	$g['language'] = 'en_US';
74
}
75

    
76
set_language($g['language']);
77

    
78
/* used by progress bar */
79
$lastseen = "-1";
80

    
81
$navlevelsep = ": ";	/* navigation level separator string */
82
$mandfldhtml = "";		/* display this before mandatory input fields */
83
$mandfldhtmlspc = "";	/* same as above, but with spacing */
84

    
85
/* Some ajax scripts still need access to GUI */
86
if(!$ignorefirmwarelock) {
87
	if (is_subsystem_dirty('firmwarelock')) {
88
		if (!$d_isfwfile) {
89
			header("Location: system_firmware.php");
90
			exit;
91
		} else {
92
			return;
93
		}
94
	}
95
}
96

    
97
/* Reserved table names to avoid colision */
98
$reserved_table_names = array(
99
        "bogons",
100
        "bogonsv6",
101
        "negate_networks",
102
        "snort2c",
103
        "sshlockout",
104
        "tonatsubnets",
105
        "virusprot",
106
        "vpn_networks",
107
        "webConfiguratorlockout"
108
);
109

    
110
$firewall_rules_dscp_types = array("af11",
111
				"af12",
112
				"af13",
113
				"af21",
114
				"af22",
115
				"af23",
116
				"af31",
117
				"af32",
118
				"af33",
119
				"af41",
120
				"af42",
121
				"af43",
122
				"VA",
123
				"EF",
124
				"cs1",
125
				"cs2",
126
				"cs3",
127
				"cs4",
128
				"cs5",
129
				"cs6",
130
				"cs7",
131
				"0x01",
132
				"0x02",
133
				"0x04");
134

    
135
$auth_server_types = array(
136
	'ldap' => "LDAP",
137
	'radius' => "Radius");
138

    
139
$ldap_urltypes = array(
140
	'TCP - Standard' => 389,
141
	'SSL - Encrypted' => 636);
142

    
143
$ldap_scopes = array(
144
	'one' => "One Level",
145
	'subtree' => "Entire Subtree");
146

    
147
$ldap_protvers = array(
148
	2,
149
	3);
150

    
151
$ldap_templates = array(
152

    
153
	'open' => array(
154
				'desc' => "OpenLDAP",
155
				'attr_user' => "cn",
156
				'attr_group' => "cn",
157
				'attr_member' => "member"),
158

    
159
	'msad' => array(
160
				'desc' => "Microsoft AD",
161
				'attr_user' => "samAccountName",
162
				'attr_group' => "cn",
163
				'attr_member' => "memberOf"),
164

    
165
	'edir' => array(
166
				'desc' => "Novell eDirectory",
167
				'attr_user' => "cn",
168
				'attr_group' => "cn",
169
				'attr_member' => "uniqueMember"));
170

    
171
$radius_srvcs = array(
172
	'both' => "Authentication and Accounting",
173
	'auth' => "Authentication",
174
	'acct' => "Accounting");
175

    
176
$netbios_nodetypes = array(
177
	'0' => "none",
178
	'1' => "b-node",
179
	'2' => "p-node",
180
	'4' => "m-node",
181
	'8' => "h-node");
182

    
183
/* some well knows ports */
184
$wkports = array(
185
	5999 => "CVSup",
186
	53 => "DNS",
187
	21 => "FTP",
188
	3000 => "HBCI",
189
	80 => "HTTP",
190
	443 => "HTTPS",
191
	5190 => "ICQ",
192
	113 => "IDENT/AUTH",
193
	143 => "IMAP",
194
	993 => "IMAP/S",
195
	4500 => "IPsec NAT-T",
196
	500 => "ISAKMP",
197
	1701 => "L2TP",
198
	389 => "LDAP",
199
	1755 => "MMS/TCP",
200
	7000 => "MMS/UDP",
201
	445 => "MS DS",
202
	3389 => "MS RDP",
203
	1512 => "MS WINS",
204
	1863 => "MSN",
205
	119 => "NNTP",
206
	123 => "NTP",
207
	138 => "NetBIOS-DGM",
208
	137 => "NetBIOS-NS",
209
	139 => "NetBIOS-SSN",
210
	1194 => "OpenVPN",
211
	110 => "POP3",
212
	995 => "POP3/S",
213
	1723 => "PPTP",
214
	1812 => "RADIUS",
215
	1813 => "RADIUS accounting",
216
	5004 => "RTP",
217
	5060 => "SIP",
218
	25 => "SMTP",
219
	465 => "SMTP/S",
220
	161 => "SNMP",
221
	162 => "SNMP-Trap",
222
	22 => "SSH",
223
	3478 => "STUN",
224
	587 => "SUBMISSION",
225
	3544 => "Teredo",
226
	23 => "Telnet",
227
	69 => "TFTP",
228
	5900 => "VNC");
229

    
230
/* TCP flags */
231
$tcpflags = array("fin", "syn", "rst", "psh", "ack", "urg", "ece", "cwr");
232

    
233
$specialnets = array("(self)" => "This Firewall", "pptp" => "PPTP clients", "pppoe" => "PPPoE clients", "l2tp" => "L2TP clients");
234

    
235
$spiflist = get_configured_interface_with_descr(false, true);
236
foreach ($spiflist as $ifgui => $ifdesc) {
237
	$specialnets[$ifgui] = $ifdesc . " net";
238
	$specialnets[$ifgui . 'ip'] = $ifdesc . " address";
239
}
240

    
241
$medias = array("auto" => "autoselect", "100full" => "100BASE-TX full-duplex",
242
	"100half" => "100BASE-TX half-duplex", "10full" => "10BASE-T full-duplex",
243
	"10half" => "10BASE-T half-duplex");
244

    
245
$wlan_modes = array("bss" => "Infrastructure (BSS)", "adhoc" => "Ad-hoc (IBSS)",
246
	"hostap" => "Access Point");
247

    
248
/* platforms that support firmware updating */
249
$fwupplatforms = array('pfSense', 'net45xx', 'net48xx', 'generic-pc', 'embedded', 'wrap', 'nanobsd');
250

    
251
function do_input_validation($postdata, $reqdfields, $reqdfieldsn, &$input_errors) {
252

    
253
	/* check for bad control characters */
254
	foreach ($postdata as $pn => $pd) {
255
		if (is_string($pd) && preg_match("/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]/", $pd)) {
256
			$input_errors[] = sprintf(gettext("The field %s contains invalid characters."), $pn);
257
		}
258
	}
259

    
260
	for ($i = 0; $i < count($reqdfields); $i++) {
261
		if ($_POST[$reqdfields[$i]] == "" && $_REQUEST[$reqdfields[$i]] == "") {
262
			$input_errors[] = sprintf(gettext("The field %s is required."), $reqdfieldsn[$i]);
263
		}
264
	}
265
}
266

    
267
function print_input_errors($input_errors) {
268
	global $g;
269

    
270
	print <<<EOF
271
	<div id="inputerrorsdiv">
272
	<table border="0" cellspacing="0" cellpadding="4" width="100%" summary="input errors">
273
	<tr>
274
		<td class="inputerrorsleft">
275
			<img src="/themes/{$g['theme']}/images/icons/icon_error.gif" alt="errors" />
276
		</td>
277
        <td class="inputerrorsright errmsg">
278
EOF;
279
    echo "<p>" . gettext("The following input errors were detected:") . "</p>\n<ul>";
280
	foreach ($input_errors as $ierr) {
281
		echo "<li>" . htmlspecialchars($ierr) . "</li>";
282
	}
283

    
284
	print <<<EOF2
285
				</ul>
286
		</td></tr>
287
	</table>
288
	</div>
289
	&nbsp;<br />
290
EOF2;
291

    
292
}
293

    
294
function verify_gzip_file($fname) {
295
	$returnvar = mwexec("/usr/bin/gzip -t " . escapeshellarg($fname));
296
	if ($returnvar != 0)
297
		return 0;
298
	else
299
		return 1;
300
}
301

    
302
function print_info_box_np($msg, $name="apply",$value="", $showapply=false) {
303
	global $g, $nifty_redbox, $nifty_blackbox, $nifty_background;
304

    
305
	if(empty($value)) {
306
		$value = gettext("Apply changes");
307
	}
308

    
309
	// Set the Nifty background color if one is not set already (defaults to white)
310
	if($nifty_background == "")
311
		$nifty_background = "#FFF";
312

    
313
	if(stristr($msg, gettext("apply")) != false || stristr($msg, gettext("save")) != false || stristr($msg, gettext("create")) != false || $showapply) {
314
		$savebutton = "<td class=\"infoboxsave\">";
315
		$savebutton .= "<input name=\"{$name}\" type=\"submit\" class=\"formbtn\" id=\"${name}\" value=\"{$value}\" />";
316
		if($_POST['if'])
317
			$savebutton .= "<input type=\"hidden\" name=\"if\" value=\"" . htmlspecialchars($_POST['if']) . "\" />";
318
		$savebutton.="</td>";
319
	}
320
	$nifty_redbox = "#990000";
321
	$nifty_blackbox = "#000000";
322

    
323
	$themename = $g['theme'];
324

    
325
	if(file_exists("/usr/local/www/themes/{$themename}/tabcontrols.php")) {
326
		$toeval = file_get_contents("/usr/local/www/themes/{$themename}/tabcontrols.php");
327
		eval($toeval);
328
	}
329

    
330
	if(file_exists("/usr/local/www/themes/{$themename}/infobox.php")) {
331
		$toeval = file_get_contents("/usr/local/www/themes/{$themename}/infobox.php");
332
		eval($toeval);
333
	}
334

    
335
	if(!$savebutton) {
336
		$savebutton = "<td class=\"infoboxsave\"><input value=\"" . gettext("Close") . "\" type=\"button\" onclick=\"jQuery(this).parents('table[id=redboxtable]').hide();\" /></td>";
337
	}
338

    
339
	echo <<<EOFnp
340
	<table class="infobox" id="redboxtable" summary="red box table">
341
		<tr>
342
			<td>
343
				<div class="infoboxnp" id="redbox">
344
					<table class="infoboxnptable2" summary="message">
345
						<tr>
346
							<td class="infoboxnptd">
347
								&nbsp;&nbsp;&nbsp;<img class="infoboxnpimg" src="/themes/{$g['theme']}/images/icons/icon_exclam.gif" alt="exclamation" />
348
							</td>
349
							<td class="infoboxnptd2">
350
								<b>{$msg}</b>
351
							</td>
352
							{$savebutton}
353
						</tr>
354
					</table>
355
				</div>
356
				<div>
357
					<p>&nbsp;</p>
358
				</div>
359
			</td>
360
		</tr>
361
	</table>
362
	<script type="text/javascript">
363
	//<![CDATA[
364
		NiftyCheck();
365
		Rounded("div#redbox","all","{$nifty_background}","{$nifty_redbox}","smooth");
366
		Rounded("td#blackbox","all","{$nifty_background}","{$nifty_blackbox}","smooth");
367
	//]]>
368
	</script>
369
EOFnp;
370

    
371
}
372

    
373
function print_info_box_np_undo($msg, $name="apply",$value="Apply changes", $undo) {
374
	global $g;
375

    
376
	if(stristr($msg, "apply") != false || stristr($msg, "save") != false || stristr($msg, "create") != false) {
377
		$savebutton = "<td class=\"infoboxsave nowrap\">";
378
		$savebutton .= "<input type=\"button\" value=\"". gettext("Undo") . "\" onclick=\"document.location='{$undo}'\" />";
379
		$savebutton .= "<input name=\"{$name}\" type=\"submit\" class=\"formbtn\" id=\"${name}\" value=\"{$value}\" />";
380
		$savebutton .= "</td>";
381
		if($_POST['if'])
382
			$savebutton .= "<input type=\"hidden\" name=\"if\" value=\"" . htmlspecialchars($_POST['if']) . "\" />";
383
	}
384
	$nifty_redbox = "#990000";
385
	$nifty_blackbox = "#000000";
386

    
387
	$themename = $g['theme'];
388

    
389
	if(file_exists("/usr/local/www/themes/{$themename}/tabcontrols.php")) {
390
		$toeval = file_get_contents("/usr/local/www/themes/{$themename}/tabcontrols.php");
391
		eval($toeval);
392
	}
393

    
394
	if(file_exists("/usr/local/www/themes/{$themename}/infobox.php")) {
395
		$toeval = file_get_contents("/usr/local/www/themes/{$themename}/infobox.php");
396
		eval($toeval);
397
	}
398

    
399

    
400
	if(!$savebutton) {
401
		$savebutton = "<td class=\"infoboxsave\"><input value=\"" . gettext("Close") . "\" type=\"button\" onclick=\"jQuery(this).parents('table[id=redboxtable]').hide();\" /></td>";
402
	}
403

    
404
	echo <<<EOFnp
405
	<table class="infobox" id="redboxtable" summary="red box table">
406
		<tr>
407
			<td>
408
				<div class="infoboxnp" id="redbox">
409
					<table class="infoboxnptable2" summary="message">
410
						<tr>
411
							<td class="infoboxnptd">
412
								&nbsp;&nbsp;&nbsp;<img class="infoboxnpimg" src="/themes/{$g['theme']}/images/icons/icon_exclam.gif" alt="exclamation" />
413
							</td>
414
							<td class="infoboxnptd2">
415
								<b>{$msg}</b>
416
							</td>
417
							{$savebutton}
418
							{$undobutton}
419
						</tr>
420
					</table>
421
				</div>
422
				<div>
423
					<p>&nbsp;</p>
424
				</div>
425
			</td>
426
		</tr>
427
	</table>
428
	<script type="text/javascript">
429
	//<![CDATA[
430
		NiftyCheck();
431
		Rounded("div#redbox","all","#FFF","{$nifty_redbox}","smooth");
432
		Rounded("td#blackbox","all","#FFF","{$nifty_blackbox}","smooth");
433
	//]]>
434
	</script>
435
EOFnp;
436

    
437
}
438

    
439
function print_info_box($msg) {
440
	print_info_box_np($msg);
441
}
442

    
443
function get_std_save_message($ok) {
444
	global $d_sysrebootreqd_path;
445
	$filter_related = false;
446
	$filter_pages = array("nat", "filter");
447
	$to_return = gettext("The changes have been applied successfully.");
448
	foreach($filter_pages as $fp)
449
		if(stristr($_SERVER['SCRIPT_FILENAME'], $fp))
450
			$filter_related = true;
451
	if($filter_related)
452
		$to_return .= "<br />" . gettext("You can also <a href=\"status_filter_reload.php\">monitor</a> the filter reload progress.");
453
	return $to_return;
454
}
455

    
456
function pprint_address($adr) {
457
	global $specialnets;
458

    
459
	if (isset($adr['any'])) {
460
		$padr = "*";
461
	} else if ($adr['network']) {
462
		$padr = $specialnets[$adr['network']];
463
	} else {
464
		$padr = $adr['address'];
465
	}
466

    
467
	if (isset($adr['not']))
468
		$padr = "! " . $padr;
469

    
470
	return $padr;
471
}
472

    
473
function pprint_port($port) {
474
	global $wkports;
475

    
476
	$pport = "";
477

    
478
	if (!$port)
479
		return "*";
480
	else {
481
		$srcport = explode("-", $port);
482
		if ((!$srcport[1]) || ($srcport[0] == $srcport[1])) {
483
			$pport = $srcport[0];
484
			if ($wkports[$srcport[0]]) {
485
				$pport .= " (" . $wkports[$srcport[0]] . ")";
486
			}
487
		} else
488
			$pport .= $srcport[0] . " - " . $srcport[1];
489
	}
490

    
491
	return $pport;
492
}
493

    
494
function firewall_check_for_advanced_options(&$item) {
495
	$item_set = "";
496
	if($item['os'])
497
		$item_set .= "os {$item['os']} ";
498
	if($item['dscp'])
499
		$item_set .= "dscp {$item['dscp']} ";
500
	if($item['max'])
501
		$item_set .= "max {$item['max']} ";
502
	if($item['max-src-nodes'])
503
		$item_set .= "max-src-nodes {$item['max-src-nodes']} ";
504
	if($item['max-src-conn'])
505
		$item_set .= "max-src-conn {$item['max-src-conn']} ";
506
	if($item['max-src-states'])
507
		$item_set .= "max-src-states {$item['max-src-states']} ";
508
	if(isset($item['nopfsync']))
509
		$item_set .= "nopfsync ";
510
	if($item['statetype'] != "keep state" && $item['statetype'] != "")
511
		$item_set .= "statetype {$item['statetype']} ";
512
	if($item['statetimeout'])
513
		$item_set .= "statetimeout {$item['statetimeout']} ";
514
	if(isset($item['nosync']))
515
		$item_set .= "no XMLRPC Sync ";
516
	if($item['max-src-conn-rate'])
517
		$item_set .= "max-src-conn-rate {$item['max-src-conn-rate']} ";
518
	if($item['max-src-conn-rates'])
519
		$item_set .= "max-src-conn-rates {$item['max-src-conn-rates']} ";
520
	if($item['vlanprio'])
521
		$item_set .= "vlanprio {$item['vlanprio']} ";
522
	if($item['vlanprioset'])
523
		$item_set .= "vlanprioset {$item['vlanprioset']} ";
524
	if($item['gateway'])
525
		$item_set .= "gateway {$item['gateway']} ";
526
	if($item['dnpipe'])
527
		$item_set .= "limiter {$item['dnpipe']} ";
528
	if($item['pdnpipe'])
529
		$item_set .= "limiter {$item['pdnpipe']} ";
530
	if($item['ackqueue'])
531
		$item_set .= "ackqueue {$item['ackqueue']} ";
532
	if($item['defaultqueue'])
533
		$item_set .= "defaultqueue {$item['defaultqueue']} ";
534
	if($item['l7container'])
535
		$item_set .= "layer7 {$item['l7container']} ";
536
	if($item['tag'])
537
		$item_set .= "tag {$item['tag']} ";
538
	if($item['tagged'])
539
		$item_set .= "tagged {$item['tagged']} ";
540
	if(isset($item['allowopts']))
541
		$item_set .= "allowopts ";
542
	if(isset($item['disablereplyto']))
543
		$item_set .= "disable reply-to ";
544
	if($item['tcpflags_any'] || $item['tcpflags1'] || $item['tcpflags2'])
545
		$item_set .= "tcpflags set";
546

    
547
	return $item_set;
548
}
549

    
550
function gentitle($title) {
551
	global $navlevelsep;
552
	if(!is_array($title))
553
		return $title;
554
	else
555
		return join($navlevelsep, $title);
556
}
557

    
558
function genhtmltitle($title) {
559
	global $config;
560
	return gentitle($title);
561
}
562

    
563
/* update the changedesc and changecount(er) variables */
564
function update_changedesc($update) {
565
	global $changedesc;
566
	global $changecount;
567

    
568
	$changedesc .= " {$update}";
569
	$changecount++;
570
}
571

    
572
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
573
	global $config, $g;
574
	if ($restart_syslogd)
575
		exec("/usr/bin/killall syslogd");
576
	if(isset($config['system']['disablesyslogclog'])) {
577
		unlink($logfile);
578
		touch($logfile);
579
	} else {
580
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
581
		if(isset($config['system']['usefifolog']))
582
			exec("/usr/sbin/fifolog_create -s {$log_size} " . escapeshellarg($logfile));
583
		else
584
			exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
585
	}
586
	if ($restart_syslogd)
587
		system_syslogd_start();
588
}
589

    
590
function clear_all_log_files() {
591
	global $g;
592
	exec("/usr/bin/killall syslogd");
593

    
594
	$log_files = array("system", "filter", "dhcpd", "vpn", "pptps", "poes", "l2tps", "openvpn", "portalauth", "ipsec", "ppp", "relayd", "wireless", "lighttpd", "ntpd", "gateways", "resolver", "routing");
595
	foreach ($log_files as $lfile) {
596
		clear_log_file("{$g['varlog_path']}/{$lfile}.log", false);
597
	}
598

    
599
	system_syslogd_start();
600
	killbyname("dhcpd");
601
	services_dhcpd_configure();
602
	return;
603
}
604

    
605
function dump_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
606
	global $g, $config;
607
	$sor = isset($config['syslog']['reverse']) ? "-r" : "";
608
	$logarr = "";
609
	$grepline = "  ";
610
	if(is_array($grepfor))
611
		$grepline .= " | /usr/bin/egrep " . escapeshellarg(implode("|", $grepfor));
612
	if(is_array($grepinvert))
613
		$grepline .= " | /usr/bin/egrep -v " . escapeshellarg(implode("|", $grepinvert));
614
	if (is_dir($logfile)) {
615
		$logarr = array("File $logfile is a directory.");
616
	} elseif (file_exists($logfile) && filesize($logfile) == 0) {
617
		$logarr = array("Log file started.");
618
	} else {
619
		if($config['system']['disablesyslogclog']) {
620
			exec("cat " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
621
		} else {
622
			if(isset($config['system']['usefifolog']))
623
				exec("/usr/sbin/fifolog_reader " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
624
			else
625
				exec("/usr/local/sbin/clog " . escapeshellarg($logfile) . "{$grepline}| grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
626
		}
627
	}
628
	foreach ($logarr as $logent) {
629
			$logent = preg_split("/\s+/", $logent, 6);
630
			echo "<tr valign=\"top\">\n";
631
			if ($withorig) {
632
					if(isset($config['system']['usefifolog'])) {
633
						$entry_date_time = htmlspecialchars(date("F j, Y, g:i a","" . $logent[1] . ""));
634
						$entry_text = htmlspecialchars($logent[5]);
635
					} else {
636
						$entry_date_time = htmlspecialchars(join(" ", array_slice($logent, 0, 3)));
637
						$entry_text = ($logent[3] ==  $config['system']['hostname']) ? "" : $logent[3] . " ";
638
						$entry_text .= htmlspecialchars($logent[4] . " " . $logent[5]);
639
					}
640
					echo "<td class=\"listlr nowrap\">{$entry_date_time}</td>\n";
641
					echo "<td class=\"listr\">{$entry_text}</td>\n";
642

    
643
			} else {
644
					echo "<td class=\"listlr\" colspan=\"2\">" . htmlspecialchars($logent[5]) . "</td>\n";
645
			}
646
			echo "</tr>\n";
647
	}
648
}
649

    
650
function return_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $grepreverse = false) {
651
	global $g, $config;
652
	$sor = (isset($config['syslog']['reverse']) || $grepreverse) ? "-r" : "";
653
	$logarr = "";
654
	$grepline = "  ";
655
	if(is_array($grepfor))
656
		$grepline .= " | /usr/bin/egrep " . escapeshellarg(implode("|", $grepfor));
657
	if(is_array($grepinvert))
658
		$grepline .= " | /usr/bin/egrep -v " . escapeshellarg(implode("|", $grepinvert));
659
	if($config['system']['disablesyslogclog']) {
660
		exec("cat " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
661
	} else {
662
		if(isset($config['system']['usefifolog'])) {
663
			exec("/usr/sbin/fifolog_reader " . escapeshellarg($logfile) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
664
		} else {
665
			exec("/usr/local/sbin/clog " . escapeshellarg($logfile) . "{$grepline}| grep -v \"CLOG\" | grep -v \"\033\" | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
666
		}
667
	}
668
	return($logarr);
669
}
670

    
671
/* Check if variable has changed, update and log if it has
672
 * returns true if var changed
673
 * varname = variable name in plain text
674
 * orig = original value
675
 * new = new value
676
 */
677
function update_if_changed($varname, & $orig, $new) {
678
	if (is_array($orig) && is_array($new)) {
679
		$a_diff = array_diff($orig, $new);
680
		foreach ($a_diff as $diff) {
681
			update_changedesc("removed {$varname}: \"{$diff}\"");
682
		}
683
		$a_diff = array_diff($new, $orig);
684
		foreach ($a_diff as $diff) {
685
			update_changedesc("added {$varname}: \"{$diff}\"");
686
		}
687
		$orig = $new;
688
		return true;
689

    
690
	} else {
691
		if ($orig != $new) {
692
			update_changedesc("{$varname}: \"{$orig}\" -> \"{$new}\"");
693
			$orig = $new;
694
			return true;
695
		}
696
	}
697
	return false;
698
}
699

    
700
function address_to_pconfig($adr, &$padr, &$pmask, &$pnot, &$pbeginport, &$pendport) {
701
	if (isset($adr['any']))
702
		$padr = "any";
703
	else if ($adr['network'])
704
		$padr = $adr['network'];
705
	else if ($adr['address']) {
706
		list($padr, $pmask) = explode("/", $adr['address']);
707
		if (!$pmask) {
708
			if (is_ipaddrv6($padr))
709
				$pmask = 128;
710
			else
711
				$pmask = 32;
712
		}
713
	}
714

    
715
	if (isset($adr['not']))
716
		$pnot = 1;
717
	else
718
		$pnot = 0;
719

    
720
	if ($adr['port']) {
721
		list($pbeginport, $pendport) = explode("-", $adr['port']);
722
		if (!$pendport)
723
			$pendport = $pbeginport;
724
	} else if (!is_alias($pbeginport) && !is_alias($pendport)) {
725
		$pbeginport = "any";
726
		$pendport = "any";
727
	}
728
}
729

    
730
function pconfig_to_address(&$adr, $padr, $pmask, $pnot=false, $pbeginport=0, $pendport=0) {
731
	$adr = array();
732

    
733
	if ($padr == "any")
734
		$adr['any'] = true;
735
	else if (is_specialnet($padr))
736
		$adr['network'] = $padr;
737
	else {
738
		$adr['address'] = $padr;
739
		if (is_ipaddrv6($padr)) {
740
			if ($pmask != 128)
741
				$adr['address'] .= "/" . $pmask;
742
		} else {
743
			if ($pmask != 32)
744
				$adr['address'] .= "/" . $pmask;
745
		}
746
	}
747

    
748
	if ($pnot)
749
		$adr['not'] = true;
750
	else
751
		unset($adr['not']);
752

    
753
	if (($pbeginport != 0) && ($pbeginport != "any")) {
754
		if ($pbeginport != $pendport)
755
			$adr['port'] = $pbeginport . "-" . $pendport;
756
		else
757
			$adr['port'] = $pbeginport;
758
	}
759

    
760
	if(is_alias($pbeginport)) {
761
		$adr['port'] = $pbeginport;
762
	}
763
}
764

    
765
function is_specialnet($net) {
766
	global $specialsrcdst;
767

    
768
	if(!$net)
769
		return false;
770
	if (in_array($net, $specialsrcdst))
771
		return true;
772
	else
773
		return false;
774
}
775

    
776
//function to create widget tabs when called
777
function display_widget_tabs(& $tab_array) {
778
	echo "<div id=\"tabs\">";
779
	$tabscounter = 0;
780
	foreach ($tab_array as $ta) {
781
	$dashpos = strpos($ta[2],'-');
782
	$tabname = $ta[2] . "-tab";
783
	$tabclass = substr($ta[2],0,$dashpos);
784
	$tabclass = $tabclass . "-class";
785
		if ($ta[1] == true) {
786
			$tabActive = "table-cell";
787
			$tabNonActive = "none";
788
		}
789
		else {
790
			$tabActive = "none";
791
			$tabNonActive = "table-cell";
792
		}
793
		echo "<div id=\"{$ta[2]}-active\" class=\"{$tabclass}-tabactive\" style=\"display:{$tabActive}; background-color:#EEEEEE; color:black;\">";
794
		echo "<b>&nbsp;&nbsp;&nbsp;{$ta[0]}";
795
		echo "&nbsp;&nbsp;&nbsp;</b>";
796
		echo "</div>";
797

    
798
		echo "<div id=\"{$ta[2]}-deactive\" class=\"{$tabclass}-tabdeactive\" style=\"display:{$tabNonActive}; background-color:#777777; color:white; cursor: pointer;\" onclick=\"return changeTabDIV('{$ta[2]}')\">";
799
		echo "<b>&nbsp;&nbsp;&nbsp;{$ta[0]}";
800
		echo "&nbsp;&nbsp;&nbsp;</b>";
801
		echo "</div>";
802
	}
803

    
804
	echo "<script type=\"text/javascript\">";
805
	echo "\n//<![CDATA[\n";
806
	echo "NiftyCheck();\n";
807
	echo "Rounded(\"div.{$tabclass}-tabactive\",\"top\",\"#CCCCCC\",\"#EEEEEE\",\"smooth\");\n";
808
	echo "Rounded(\"div.{$tabclass}-tabdeactive\",\"top\",\"#CCCCCC\",\"#777777\",\"smooth\");\n";
809
	echo "//]]>\n";
810
	echo "</script>";
811
	echo "</div>";
812
}
813

    
814

    
815
// Return inline javascript file or CSS to minimizie
816
// request count going back to server.
817
function outputJavaScriptFileInline($javascript) {
818
	if(file_exists($javascript)) {
819
		echo "\n<script type=\"text/javascript\">\n";
820
		include($javascript);
821
		echo "\n</script>\n";
822
	} else {
823
		echo "\n\n<!-- Could not location file:  {$javascript} -->\n\n";
824
	}
825
}
826

    
827

    
828

    
829
function outputCSSPrintFileInline($css) {
830
	if(file_exists($css)) {
831
		echo "\n<style media=\"print\" type=\"text/css\">\n";
832
		include($css);
833
		echo "\n</style>\n";
834
	} else {
835
		echo "\n\n<!-- Could not location file:  {$css} -->\n\n";
836
	}
837
}
838

    
839

    
840
function outputCSSFileInline($css) {
841
	if(file_exists($css)) {
842
		echo "\n<style type=\"text/css\">\n";
843
		include($css);
844
		echo "\n</style>\n";
845
	} else {
846
		echo "\n\n<!-- Could not location file:  {$css} -->\n\n";
847
	}
848
}
849

    
850
$rfc2616 = array(
851
	100 => "100 Continue",
852
	101 => "101 Switching Protocols",
853
	200 => "200 OK",
854
	201 => "201 Created",
855
	202 => "202 Accepted",
856
	203 => "203 Non-Authoritative Information",
857
	204 => "204 No Content",
858
	205 => "205 Reset Content",
859
	206 => "206 Partial Content",
860
	300 => "300 Multiple Choices",
861
	301 => "301 Moved Permanently",
862
	302 => "302 Found",
863
	303 => "303 See Other",
864
	304 => "304 Not Modified",
865
	305 => "305 Use Proxy",
866
	306 => "306 (Unused)",
867
	307 => "307 Temporary Redirect",
868
	400 => "400 Bad Request",
869
	401 => "401 Unauthorized",
870
	402 => "402 Payment Required",
871
	403 => "403 Forbidden",
872
	404 => "404 Not Found",
873
	405 => "405 Method Not Allowed",
874
	406 => "406 Not Acceptable",
875
	407 => "407 Proxy Authentication Required",
876
	408 => "408 Request Timeout",
877
	409 => "409 Conflict",
878
	410 => "410 Gone",
879
	411 => "411 Length Required",
880
	412 => "412 Precondition Failed",
881
	413 => "413 Request Entity Too Large",
882
	414 => "414 Request-URI Too Long",
883
	415 => "415 Unsupported Media Type",
884
	416 => "416 Requested Range Not Satisfiable",
885
	417 => "417 Expectation Failed",
886
	500 => "500 Internal Server Error",
887
	501 => "501 Not Implemented",
888
	502 => "502 Bad Gateway",
889
	503 => "503 Service Unavailable",
890
	504 => "504 Gateway Timeout",
891
	505 => "505 HTTP Version Not Supported"
892
);
893

    
894
function is_rfc2616_code($code) {
895
	global $rfc2616;
896
	if (isset($rfc2616[$code]))
897
		return true;
898
	else
899
		return false;
900
}
901

    
902
function print_rfc2616_select($tag, $current){
903
	global $rfc2616;
904

    
905
	/* Default to 200 OK if not set */
906
	if ($current == "")
907
		$current = 200;
908

    
909
	echo "<select id=\"{$tag}\" name=\"{$tag}\">\n";
910
	foreach($rfc2616 as $code => $message) {
911
		if ($code == $current) {
912
			$sel = " selected=\"selected\"";
913
		} else {
914
			$sel = "";
915
		}
916
		echo "<option value=\"{$code}\"{$sel}>{$message}</option>\n";
917
	}
918
	echo "</select>\n";
919
}
920

    
921
// Useful debugging function, much cleaner than print_r
922
function echo_array($array,$return_me=false){
923
	if(is_array($array) == false){
924
		$return = "The provided variable is not an array.";
925
	}else{
926
		foreach($array as $name=>$value){
927
			if(is_array($value)){
928
				$return .= "";
929
				$return .= "['<b>$name</b>'] {<div style=\"margin-left:10px;\">\n";
930
				$return .= echo_array($value,true);
931
				$return .= "</div>}";
932
				$return .= "\n\n";
933
			}else{
934
				if(is_string($value)){
935
					$value = "\"$value\"";
936
				}
937
				$return .= "['<b>$name</b>'] = $value\n\n";
938
			}
939
		}
940
	}
941
	if($return_me == true){
942
		return $return;
943
	}else{
944
		echo "<pre>".$return."</pre>";
945
	}
946
}
947

    
948
/****f* pfsense-utils/display_top_tabs
949
 * NAME
950
 *   display_top_tabs - display tabs with rounded edges
951
 * INPUTS
952
 *   $text      - array of tabs
953
 * RESULT
954
 *   null
955
 ******/
956
function display_top_tabs(& $tab_array, $no_drop_down = false) {
957
	global $config;
958
	global $g;
959
	global $tab_array_indent;
960
	global $tab_array_space;
961
	global $tab_array_char_limit;
962

    
963
	/*  does the user have access to this tab?
964
	 *  master user has access to everything.
965
	 *  if the user does not have access, simply
966
	 *  unset the tab item.
967
	 */
968

    
969
	/* empty string code */
970
	if ($tab_array_indent == '') {
971
		$tab_array_indent = 0;
972
	}
973

    
974
	if ($tab_array_space == '') {
975
		$tab_array_space = 1;
976
	}
977

    
978
	if ($tab_array_char_limit == '') {
979
		$tab_array_char_limit = 92;
980
	}
981

    
982
	foreach ($tab_array as $tab_id => $ta){
983
		if(!isAllowedPage($ta[2]))
984
			unset ($tab_array[$tab_id]);
985
	}
986

    
987
	$tab_active_bg   = "#EEEEEE";
988
	$tab_inactive_bg = "#777777";
989
	$nifty_tabs_corners = "#FFF";
990
	$font_color = "white";
991

    
992
	/* if tabcontrols.php exist for a theme, allow it to be overriden */
993
	$themename = $config['theme'];
994
	$filename = "/usr/local/www/themes/{$themename}/tabcontrols.php";
995
	if(file_exists($filename)) {
996
		$eval_code = file_get_contents($filename);
997
		eval($eval_code);
998
	}
999

    
1000
	$tabcharcount = 0;
1001
	foreach ($tab_array as $ta)
1002
		$tabcharcount = $tabcharcount + strlen($ta[0]);
1003

    
1004
	if($no_drop_down == true) {
1005
		$tabcharcount = 0;
1006
		unset($tab_array_char_limit);
1007
	}
1008

    
1009
	// If the character count of the tab names is > 670
1010
	// then show a select item dropdown menubox.
1011
	if($tabcharcount > $tab_array_char_limit) {
1012
		echo gettext("Currently viewing: ");
1013
		echo "<select name=\"TabSelect\" onchange=\"tabs_will_go(this)\">\n";
1014
		foreach ($tab_array as $ta) {
1015
			if($ta[1]=="true")
1016
				$selected = " selected=\"selected\"";
1017
			else
1018
				$selected = "";
1019
			// Onclick in option will not work in some browser
1020
			// echo "<option onclick=\"document.location='{$ta[2]}';\"{$selected}>{$ta['0']}</option>\n";
1021
			echo "<option value=\"{$ta[2]}\"{$selected}>{$ta['0']}</option>\n";
1022
		}
1023
		echo "</select>\n<p>&nbsp;</p>";
1024
		echo "<script type=\"text/javascript\">";
1025
		echo "\n//<![CDATA[\n";
1026
		echo " function tabs_will_go(obj){ document.location = obj.value; }\n";
1027
		echo "//]]>\n";
1028
		echo "</script>";
1029
	}  else {
1030
		echo "<div class=\"newtabmenu\" style=\"margin:{$tab_array_space}px {$tab_array_indent}px; width:775px;\">\n";
1031
		echo "<!-- Tabbed bar code-->\n";
1032
		echo "<ul class=\"newtabmenu\">\n";
1033
		$tabscounter = 0;
1034
		foreach ($tab_array as $ta) {
1035
			if ($ta[1] == true) {
1036
				echo "  <li class=\"newtabmenu_active\"><a href=\"{$ta[2]}\"><span>{$ta[0]}</span></a></li>\n";
1037
			} else {
1038
				echo "  <li><a href=\"{$ta[2]}\"><span>{$ta[0]}</span></a></li>\n";
1039
			}
1040
			$tabscounter++;
1041
		}
1042
		echo "</ul>\n</div>\n";
1043
	}
1044
}
1045

    
1046
function add_package_tabs($tabgroup, & $tab_array) {
1047
	global $config, $g;
1048

    
1049
	if(!is_array($config['installedpackages']))
1050
		return;
1051
	if(!is_array($config['installedpackages']['tab']))
1052
		return;
1053

    
1054
	foreach($config['installedpackages']['tab'] as $tab) {
1055
		if ($tab['group'] !== $group)
1056
			continue;
1057
		$tab_entry = array();
1058
		if($tab['name']) {
1059
			$tab_entry[] = $tab['name'];
1060
			$tab_entry[] = false;
1061
			$tab_entry[] = $tab['url'];
1062
			$tab_array[] = $tab_entry;
1063
		}
1064
	}
1065
}
1066

    
1067
function alias_info_popup($alias_id){
1068
	global $config;
1069
	$maxlength = 60;
1070
	$close_title="title='".gettext('move mouse out this alias to hide')."'";
1071
	if (is_array($config['aliases']['alias'][$alias_id])){
1072
		$alias_name=$config['aliases']['alias'][$alias_id];
1073
		$alias_objects_with_details = "<table width=\"100%\" border=\"0\" cellpadding=\"2\" cellspacing=\"0\" summary=\"alias info popup\">";
1074
		if ($alias_name['url']) {
1075
			// TODO: Change it when pf supports tables with ports
1076
			if ($alias_name['type'] == "urltable") {
1077
				exec("/sbin/pfctl -t {$alias_name['name']} -T show | wc -l", $total_entries);
1078
				$counter=preg_replace("/\D/","",$total_entries[0]);
1079
				exec("/sbin/pfctl -t {$alias_name['name']} -T show | head -10002", $alias_addresses);
1080
			} else {
1081
				$urlfn = alias_expand_urltable($alias_name['name']);
1082
				$alias_addresses = explode("\n", file_get_contents($urlfn));
1083
				$counter = count($alias_addresses);
1084
			}
1085
			$alias_objects_with_details .= "<tr><td colspan=\"3\" $close_title class=\"vncell\">{$alias_name['url']}</td></tr>";
1086
			$x=0;
1087
			foreach ($alias_addresses as $alias_ports_address ) {
1088
				switch ($x) {
1089
				case 0:
1090
					$x++;
1091
					$alias_objects_with_details .= "<tr><td $close_title class=\"vncell\" width=\"33%\" style=\"background: #FFFFFF;color: #000000;\">{$alias_ports_address}</td>";
1092
					break;
1093
				case 1:
1094
					$x++;
1095
					$alias_objects_with_details .= "<td $close_title class=\"vncell\" width=\"33%\" style=\"background: #FFFFFF;color: #000000;\">{$alias_ports_address}</td>";
1096
					break;
1097
				default:
1098
					$x=0;
1099
					$alias_objects_with_details .= "<td  $close_title class=\"vncell\" width=\"33%\" style=\"background: #FFFFFF;color: #000000;\">{$alias_ports_address}</td><tr>";
1100
					break;
1101
				}
1102
			}
1103
			for ($y = $x; $y <= $x; $y++) {
1104
				$alias_objects_with_details .= "<td $close_title class=\"vncell\" width=\"33%\">&nbsp;</td>";
1105
			}
1106
			if ($x > 0) {
1107
				$alias_objects_with_details .= "</tr>";
1108
			}
1109
			if ($counter > 10002) {
1110
				$alias_objects_with_details .= "<tr><td colspan=\"3\"> ". gettext("listing only first 10k items") . "</td><tr>";
1111
			}
1112
		}
1113
		else{
1114
			$alias_addresses = explode (" ", $alias_name['address']);
1115
			$alias_details = explode ("||", $alias_name['detail']);
1116
			$counter = 0;
1117
			foreach ($alias_addresses as $alias_ports_address) {
1118
				$alias_objects_with_details .= "<tr><td $close_title width=\"5%\" class=\"vncell\" style=\"background: #FFFFFF;color: #000000;\">{$alias_addresses[$counter]}</td>";
1119
				$alias_detail_default = strpos ($alias_details[$counter],"Entry added");
1120
				if ($alias_details[$counter] != "" && $alias_detail_default === False)
1121
					$alias_objects_with_details .="<td $close_title width=\"95%\" class=\"vncell\" style=\"background: #FFFFFF;color: #000000;\">{$alias_details[$counter]}</td>";
1122
				else
1123
					$alias_objects_with_details .="<td $close_title width=\"95%\" class=\"vncell\" style=\"background: #FFFFFF;color: #000000;\">&nbsp;</td>";
1124
				$alias_objects_with_details .= "</tr>";
1125
				$counter++;
1126
			}
1127
		}
1128
		$alias_objects_with_details .= "</table>";
1129
	}
1130
	$alias_descr_substr = $alias_name['descr'];
1131
	if ($strlength >= $maxlength)
1132
		$alias_descr_substr = substr($alias_descr_substr, 0, $maxlength) . "...";
1133
	$item_text = ($counter > 1 ? "items" : "item");
1134
	$alias_caption = "{$alias_descr_substr} - {$counter} {$item_text}<a href=\"/firewall_aliases_edit.php?id={$alias_id}\" title=\"".gettext('edit this alias')."\">&nbsp;&nbsp;edit </a>";
1135
	$strlength = strlen ($alias_caption);
1136
	print "<h1>{$alias_caption}</h1>" . $alias_objects_with_details;
1137
}
1138

    
1139
function rule_popup($src,$srcport,$dst,$dstport){
1140
	global $config,$g;
1141
	$aliases_array = array();
1142
	if ($config['aliases']['alias'] <> "" and is_array($config['aliases']['alias'])) {
1143
		$descriptions = array ();
1144
		foreach ($config['aliases']['alias'] as $alias_id=>$alias_name){
1145
			$loading_image="<a><img src=\'/themes/{$g['theme']}/images/misc/loader.gif\' alt=\'loader\' /> " .gettext("loading...")."</a>";
1146
			switch ($alias_name['type']){
1147
			case "port":
1148
				$width="250";
1149
				break;
1150
			case "urltable":
1151
				$width="500";
1152
				break;
1153
			default:
1154
				$width="350";
1155
				break;
1156
			}
1157
			$span_begin = "<span style=\"cursor: help;\" onmouseover=\"var response_html=domTT_activate(this, event, 'id','ttalias_{$alias_id}','content','{$loading_image}', 'trail', true, 'delay', 300, 'fade', 'both', 'fadeMax', 93, 'styleClass', 'niceTitle','type','velcro','width',{$width});alias_popup('{$alias_id}','{$g['theme']}','".gettext('loading...')."');\" onmouseout=\"this.style.color = ''; domTT_mouseout(this, event);\"><u>";
1158
			$span_end = "</u></span>";
1159
			if ($alias_name['name'] == $src) {
1160
				$descriptions['src'] = $span_begin;
1161
				$descriptions['src_end'] = $span_end;
1162
			}
1163
			if ($alias_name['name'] == $srcport) {
1164
				$descriptions['srcport'] = $span_begin;
1165
				$descriptions['srcport_end'] = $span_end;
1166
			}
1167
			if ($alias_name['name'] == $dst ) {
1168
				$descriptions['dst'] = $span_begin;
1169
				$descriptions['dst_end'] = $span_end;
1170
			}
1171
			if ($alias_name['name'] == $dstport) {
1172
				$descriptions['dstport'] = $span_begin;
1173
				$descriptions['dstport_end'] = $span_end;
1174
			}
1175
		}
1176
		return $descriptions;
1177
	}
1178
}
1179

    
1180
$timezone = $config['system']['timezone'];
1181
if (!$timezone)
1182
	$timezone = "Etc/UTC";
1183

    
1184
date_default_timezone_set($timezone);
1185

    
1186
?>
(88-88/256)