Project

General

Profile

Download (99.1 KB) Statistics
| Branch: | Tag: | Revision:
1 14227c51 Scott Ullrich
<?php
2 09221bc3 Renato Botelho
/*
3 8acd654a Renato Botelho
 * pfsense-utils.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6 2a2396a6 Renato Botelho
 * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
7 8acd654a Renato Botelho
 * All rights reserved.
8
 *
9
 * Redistribution and use in source and binary forms, with or without
10
 * modification, are permitted provided that the following conditions are met:
11
 *
12
 * 1. Redistributions of source code must retain the above copyright notice,
13
 *    this list of conditions and the following disclaimer.
14
 *
15
 * 2. Redistributions in binary form must reproduce the above copyright
16
 *    notice, this list of conditions and the following disclaimer in
17
 *    the documentation and/or other materials provided with the
18
 *    distribution.
19
 *
20
 * 3. All advertising materials mentioning features or use of this software
21
 *    must display the following acknowledgment:
22
 *    "This product includes software developed by the pfSense Project
23
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
24
 *
25
 * 4. The names "pfSense" and "pfSense Project" must not be used to
26
 *    endorse or promote products derived from this software without
27
 *    prior written permission. For written permission, please contact
28
 *    coreteam@pfsense.org.
29
 *
30
 * 5. Products derived from this software may not be called "pfSense"
31
 *    nor may "pfSense" appear in their names without prior written
32
 *    permission of the Electric Sheep Fencing, LLC.
33
 *
34
 * 6. Redistributions of any form whatsoever must retain the following
35
 *    acknowledgment:
36
 *
37
 * "This product includes software developed by the pfSense Project
38
 * for use in the pfSense software distribution (http://www.pfsense.org/).
39
 *
40
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
41
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
44
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51
 * OF THE POSSIBILITY OF SUCH DAMAGE.
52
 */
53 3076becf Scott Ullrich
54 0397013a Scott Ullrich
/****f* pfsense-utils/have_natpfruleint_access
55
 * NAME
56
 *   have_natpfruleint_access
57
 * INPUTS
58 c96e71d1 Renato Botelho
 *	none
59 0397013a Scott Ullrich
 * RESULT
60
 *   returns true if user has access to edit a specific firewall nat port forward interface
61
 ******/
62
function have_natpfruleint_access($if) {
63
	$security_url = "firewall_nat_edit.php?if=". strtolower($if);
64 23a193da Phil Davis
	if (isAllowedPage($security_url, $allowed)) {
65 0397013a Scott Ullrich
		return true;
66 23a193da Phil Davis
	}
67 0397013a Scott Ullrich
	return false;
68
}
69
70 b6742927 Scott Ullrich
/****f* pfsense-utils/have_ruleint_access
71
 * NAME
72
 *   have_ruleint_access
73
 * INPUTS
74 c96e71d1 Renato Botelho
 *	none
75 b6742927 Scott Ullrich
 * RESULT
76
 *   returns true if user has access to edit a specific firewall interface
77
 ******/
78
function have_ruleint_access($if) {
79
	$security_url = "firewall_rules.php?if=". strtolower($if);
80 23a193da Phil Davis
	if (isAllowedPage($security_url)) {
81 45ee90ed Matthew Grooms
		return true;
82 23a193da Phil Davis
	}
83 b6742927 Scott Ullrich
	return false;
84
}
85
86 10387862 Scott Ullrich
/****f* pfsense-utils/does_url_exist
87
 * NAME
88
 *   does_url_exist
89
 * INPUTS
90 c96e71d1 Renato Botelho
 *	none
91 10387862 Scott Ullrich
 * RESULT
92
 *   returns true if a url is available
93
 ******/
94
function does_url_exist($url) {
95 4de8f7ba Phil Davis
	$fd = fopen("$url", "r");
96 23a193da Phil Davis
	if ($fd) {
97 4cc6345e Scott Ullrich
		fclose($fd);
98 5fa78adc Renato Botelho
		return true;
99 10387862 Scott Ullrich
	} else {
100 5fa78adc Renato Botelho
		return false;
101 10387862 Scott Ullrich
	}
102
}
103
104 5928bd75 Scott Ullrich
/****f* pfsense-utils/is_private_ip
105
 * NAME
106
 *   is_private_ip
107
 * INPUTS
108 c96e71d1 Renato Botelho
 *	none
109 5928bd75 Scott Ullrich
 * RESULT
110
 *   returns true if an ip address is in a private range
111
 ******/
112
function is_private_ip($iptocheck) {
113 5fa78adc Renato Botelho
	$isprivate = false;
114 4de8f7ba Phil Davis
	$ip_private_list = array(
115 5fa78adc Renato Botelho
		"10.0.0.0/8",
116
		"100.64.0.0/10",
117
		"172.16.0.0/12",
118
		"192.168.0.0/16",
119
	);
120 23a193da Phil Davis
	foreach ($ip_private_list as $private) {
121 4de8f7ba Phil Davis
		if (ip_in_subnet($iptocheck, $private) == true) {
122 5fa78adc Renato Botelho
			$isprivate = true;
123 23a193da Phil Davis
		}
124 5fa78adc Renato Botelho
	}
125
	return $isprivate;
126 5928bd75 Scott Ullrich
}
127
128 8cb370b9 Scott Ullrich
/****f* pfsense-utils/get_tmp_file
129
 * NAME
130
 *   get_tmp_file
131
 * INPUTS
132 c96e71d1 Renato Botelho
 *	none
133 8cb370b9 Scott Ullrich
 * RESULT
134
 *   returns a temporary filename
135
 ******/
136 3076becf Scott Ullrich
function get_tmp_file() {
137 da17d77e Ermal Lu?i
	global $g;
138
	return "{$g['tmp_path']}/tmp-" . time();
139 3076becf Scott Ullrich
}
140
141
/****f* pfsense-utils/get_dns_servers
142
 * NAME
143 0057e62d Chris Buechler
 *   get_dns_servers - get system dns servers
144 3076becf Scott Ullrich
 * INPUTS
145 0057e62d Chris Buechler
 *   none
146 3076becf Scott Ullrich
 * RESULT
147 0057e62d Chris Buechler
 *   $dns_servers - an array of the dns servers
148 3076becf Scott Ullrich
 ******/
149
function get_dns_servers() {
150
	$dns_servers = array();
151 0057e62d Chris Buechler
	if (file_exists("/etc/resolv.conf")) {
152 4de8f7ba Phil Davis
		$dns_s = file("/etc/resolv.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
153 0057e62d Chris Buechler
	}
154
	if (is_array($dns_s)) {
155 4de8f7ba Phil Davis
		foreach ($dns_s as $dns) {
156
			$matches = "";
157
			if (preg_match("/nameserver (.*)/", $dns, $matches)) {
158
				$dns_servers[] = $matches[1];
159
			}
160 23a193da Phil Davis
		}
161 3076becf Scott Ullrich
	}
162 fa112436 Ermal
	return array_unique($dns_servers);
163 3076becf Scott Ullrich
}
164
165 595b074d Phil Davis
/****f* pfsense-utils/get_css_files
166
 * NAME
167
 *   get_css_files - get a list of the available CSS files (themes)
168
 * INPUTS
169
 *   none
170
 * RESULT
171
 *   $csslist - an array of the CSS files
172
 ******/
173
function get_css_files() {
174
	$csslist = array();
175
176
	// List pfSense files, then any BETA files followed by any user-contributed files
177
	$cssfiles = glob("/usr/local/www/css/*.css");
178
179
	if (is_array($cssfiles)) {
180
		arsort($cssfiles);
181
		$usrcss = $pfscss = $betacss = array();
182
183
		foreach ($cssfiles as $css) {
184
			if (strpos($css, "BETA") != 0) {
185
				array_push($betacss, $css);
186
			} else if (strpos($css, "pfSense") != 0) {
187
				array_push($pfscss, $css);
188
			} else {
189
				array_push($usrcss, $css);
190
			}
191
		}
192
193
		$css = array_merge($pfscss, $betacss, $usrcss);
194
195
		foreach ($css as $file) {
196
			$file = basename($file);
197
			$csslist[$file] = pathinfo($file, PATHINFO_FILENAME);
198
		}
199
	}
200
	return $csslist;
201
}
202
203
/****f* pfsense-utils/gen_webguicss_field
204
 * NAME
205
 *   gen_webguicss_field
206
 * INPUTS
207
 *   Pointer to section object
208
 *   Initial value for the field
209
 * RESULT
210
 *   no return value, section object is updated
211
 ******/
212
function gen_webguicss_field(&$section, $value) {
213
214
	$csslist = get_css_files();
215
216
	if (!isset($csslist[$value])) {
217
		$value = "pfSense.css";
218
	}
219
220
	$section->addInput(new Form_Select(
221
		'webguicss',
222
		'Theme',
223
		$value,
224
		$csslist
225
	))->setHelp(sprintf(gettext('Choose an alternative css file (if installed) to change the appearance of the webConfigurator. css files are located in /usr/local/www/css/%s'), '<span id="csstxt"></span>'));
226
}
227
228
/****f* pfsense-utils/gen_webguifixedmenu_field
229
 * NAME
230
 *   gen_webguifixedmenu_field
231
 * INPUTS
232
 *   Pointer to section object
233
 *   Initial value for the field
234
 * RESULT
235
 *   no return value, section object is updated
236
 ******/
237
function gen_webguifixedmenu_field(&$section, $value) {
238
239
	$section->addInput(new Form_Select(
240
		'webguifixedmenu',
241
		'Top Navigation',
242
		$value,
243
		["" => gettext("Scrolls with page"), "fixed" => gettext("Fixed (Remains visible at top of page)")]
244
	))->setHelp("The fixed option is intended for large screens only.");
245
}
246
247
/****f* pfsense-utils/gen_webguihostnamemenu_field
248
 * NAME
249
 *   gen_webguihostnamemenu_field
250
 * INPUTS
251
 *   Pointer to section object
252
 *   Initial value for the field
253
 * RESULT
254
 *   no return value, section object is updated
255
 ******/
256
function gen_webguihostnamemenu_field(&$section, $value) {
257
258
	$section->addInput(new Form_Select(
259
		'webguihostnamemenu',
260
		'Hostname in Menu',
261
		$value,
262
		["" => gettext("Default (No hostname)"), "hostonly" => gettext("Hostname only"), "fqdn" => gettext("Fully Qualified Domain Name")]
263
	))->setHelp("Replaces the Help menu title in the Navbar with the system hostname or FQDN.");
264
}
265
266
/****f* pfsense-utils/gen_dashboardcolumns_field
267
 * NAME
268
 *   gen_dashboardcolumns_field
269
 * INPUTS
270
 *   Pointer to section object
271
 *   Initial value for the field
272
 * RESULT
273
 *   no return value, section object is updated
274
 ******/
275
function gen_dashboardcolumns_field(&$section, $value) {
276
277
	if (($value < 1) || ($value > 4)) {
278
		$value = 2;
279
	}
280
281
	$section->addInput(new Form_Input(
282
		'dashboardcolumns',
283
		'Dashboard Columns',
284
		'number',
285
		$value,
286
		[min => 1, max => 4]
287
	));
288
}
289
290 3666d731 Phil Davis
/****f* pfsense-utils/gen_interfacessort_field
291
 * NAME
292
 *   gen_interfacessort_field
293
 * INPUTS
294
 *   Pointer to section object
295
 *   Initial value for the field
296
 * RESULT
297
 *   no return value, section object is updated
298
 ******/
299
function gen_interfacessort_field(&$section, $value) {
300
301
	$section->addInput(new Form_Checkbox(
302
		'interfacessort',
303
		'Interfaces Sort',
304
		'Sort Alphabetically',
305
		$value
306
	))->setHelp('If selected, lists of interfaces will be sorted by description, otherwise they are listed wan,lan,optn...');
307
}
308
309 595b074d Phil Davis
/****f* pfsense-utils/gen_associatedpanels_fields
310
 * NAME
311
 *   gen_associatedpanels_fields
312
 * INPUTS
313
 *   Pointer to section object
314
 *   Initial value for each of the fields
315
 * RESULT
316
 *   no return value, section object is updated
317
 ******/
318
function gen_associatedpanels_fields(&$section, $value1, $value2, $value3, $value4) {
319
320
	$group = new Form_Group('Associated Panels Show/Hide');
321
322
	$group->add(new Form_Checkbox(
323
		'dashboardavailablewidgetspanel',
324
		null,
325
		'Available Widgets',
326
		$value1
327
		))->setHelp('Show the Available Widgets panel on the Dashboard.');
328
329
	$group->add(new Form_Checkbox(
330
		'systemlogsfilterpanel',
331
		null,
332
		'Log Filter',
333
		$value2
334
	))->setHelp('Show the Log Filter panel in System Logs.');
335
336
	$group->add(new Form_Checkbox(
337
		'systemlogsmanagelogpanel',
338
		null,
339
		'Manage Log',
340
		$value3
341
	))->setHelp('Show the Manage Log panel in System Logs.');
342
343
	$group->add(new Form_Checkbox(
344
		'statusmonitoringsettingspanel',
345
		null,
346
		'Monitoring Settings',
347
		$value4
348
	))->setHelp('Show the Settings panel in Status Monitoring.');
349
350
	$group->setHelp('These options allow certain panels to be automatically hidden on page load. A control is provided in the title bar to un-hide the panel.');
351
352
	$section->add($group);
353
}
354
355
/****f* pfsense-utils/gen_webguileftcolumnhyper_field
356
 * NAME
357
 *   gen_webguileftcolumnhyper_field
358
 * INPUTS
359
 *   Pointer to section object
360
 *   Initial value for the field
361
 * RESULT
362
 *   no return value, section object is updated
363
 ******/
364
function gen_webguileftcolumnhyper_field(&$section, $value) {
365
366
	$section->addInput(new Form_Checkbox(
367
		'webguileftcolumnhyper',
368
		'Left Column Labels',
369
		'Active',
370
		$value
371
	))->setHelp('If selected, clicking a label in the left column will select/toggle the first item of the group.');
372
}
373
374
/****f* pfsense-utils/gen_pagenamefirst_field
375
 * NAME
376
 *   gen_pagenamefirst_field
377
 * INPUTS
378
 *   Pointer to section object
379
 *   Initial value for the field
380
 * RESULT
381
 *   no return value, section object is updated
382
 ******/
383
function gen_pagenamefirst_field(&$section, $value) {
384
385
	$section->addInput(new Form_Checkbox(
386
		'pagenamefirst',
387
		'Browser tab text',
388
		'Display page name first in browser tab',
389
		$value
390
	))->setHelp('When this is unchecked, the browser tab shows the host name followed '.
391
		'by the current page. Check this box to display the current page followed by the '.
392
		'host name.');
393
}
394
395
/****f* pfsense-utils/gen_user_settings_fields
396
 * NAME
397
 *   gen_user_settings_fields
398
 * INPUTS
399
 *   Pointer to section object
400
 *   Array of initial values for the fields
401
 * RESULT
402
 *   no return value, section object is updated
403
 ******/
404
function gen_user_settings_fields(&$section, $pconfig) {
405
406
	gen_webguicss_field($section, $pconfig['webguicss']);
407
	gen_webguifixedmenu_field($section, $pconfig['webguifixedmenu']);
408
	gen_webguihostnamemenu_field($section, $pconfig['webguihostnamemenu']);
409
	gen_dashboardcolumns_field($section, $pconfig['dashboardcolumns']);
410 3666d731 Phil Davis
	gen_interfacessort_field($section, $pconfig['interfacessort']);
411 595b074d Phil Davis
	gen_associatedpanels_fields(
412
		$section,
413
		$pconfig['dashboardavailablewidgetspanel'],
414
		$pconfig['systemlogsfilterpanel'],
415
		$pconfig['systemlogsmanagelogpanel'],
416
		$pconfig['statusmonitoringsettingspanel']);
417
	gen_webguileftcolumnhyper_field($section, $pconfig['webguileftcolumnhyper']);
418
	gen_pagenamefirst_field($section, $pconfig['pagenamefirst']);
419
}
420
421 05a13eba derelict-pf
/****f* pfsense-utils/gen_requirestatefilter_field
422
 * NAME
423
 *   gen_requirestatefilter_field
424
 * INPUTS
425
 *   Pointer to section object
426
 *   Initial value for the field
427
 * RESULT
428
 *   no return value, section object is updated
429
 ******/
430
function gen_requirestatefilter_field(&$section, $value) {
431
	$section->addInput(new Form_Checkbox(
432
		'requirestatefilter',
433
		'Require State Filter',
434
		'Do not display state table without a filter',
435
		$value
436
	))->setHelp('By default, the entire state table is displayed when entering '.
437
		'Diagnostics > States. This option requires a filter to be entered '.
438
		'before the states are displayed. Useful for systems with large state tables.');
439
}
440
441 4c4504b1 Phil Davis
/****f* pfsense-utils/gen_created_updated_fields
442
 * NAME
443
 *   gen_created_updated_fields
444
 * INPUTS
445
 *   Pointer to form object
446
 *   Array of created time and username
447
 *   Array of updated time and username
448
 * RESULT
449
 *   no return value, section object is added to form if needed
450
 ******/
451
function gen_created_updated_fields(&$form, $created, $updated) {
452
	$has_created_time = (isset($created['time']) && isset($created['username']));
453
	$has_updated_time = (isset($updated['time']) && isset($updated['username']));
454
455
	if ($has_created_time || $has_updated_time) {
456
		$section = new Form_Section('Rule Information');
457
458
		if ($has_created_time) {
459
			$section->addInput(new Form_StaticText(
460
				'Created',
461
				sprintf(
462
					gettext('%1$s by %2$s'),
463
					date(gettext("n/j/y H:i:s"), $created['time']),
464
					$created['username'])
465
			));
466
		}
467
468
		if ($has_updated_time) {
469
			$section->addInput(new Form_StaticText(
470
				'Updated',
471
				sprintf(
472
					gettext('%1$s by %2$s'),
473
					date(gettext("n/j/y H:i:s"), $updated['time']),
474
					$updated['username'])
475
			));
476
		}
477
478
		$form->add($section);
479
	}
480
}
481
482 43517fcc Ermal LUÇI
function hardware_offloading_applyflags($iface) {
483
	global $config;
484
485
	$flags_on = 0;
486
	$flags_off = 0;
487
	$options = pfSense_get_interface_addresses($iface);
488
489 23a193da Phil Davis
	if (isset($config['system']['disablechecksumoffloading'])) {
490
		if (isset($options['encaps']['txcsum'])) {
491 43517fcc Ermal LUÇI
			$flags_off |= IFCAP_TXCSUM;
492 23a193da Phil Davis
		}
493
		if (isset($options['encaps']['rxcsum'])) {
494 43517fcc Ermal LUÇI
			$flags_off |= IFCAP_RXCSUM;
495 23a193da Phil Davis
		}
496 ebc4a441 Luiz Otavio O Souza
		if (isset($options['encaps']['txcsum6'])) {
497
			$flags_off |= IFCAP_TXCSUM_IPV6;
498
		}
499
		if (isset($options['encaps']['rxcsum6'])) {
500
			$flags_off |= IFCAP_RXCSUM_IPV6;
501
		}
502 43517fcc Ermal LUÇI
	} else {
503 bc4d752b jim-p
		if (isset($options['caps']['txcsum'])) {
504 43517fcc Ermal LUÇI
			$flags_on |= IFCAP_TXCSUM;
505 23a193da Phil Davis
		}
506 bc4d752b jim-p
		if (isset($options['caps']['rxcsum'])) {
507 43517fcc Ermal LUÇI
			$flags_on |= IFCAP_RXCSUM;
508 23a193da Phil Davis
		}
509 ebc4a441 Luiz Otavio O Souza
		if (isset($options['caps']['txcsum6'])) {
510
			$flags_on |= IFCAP_TXCSUM_IPV6;
511
		}
512
		if (isset($options['caps']['rxcsum6'])) {
513
			$flags_on |= IFCAP_RXCSUM_IPV6;
514
		}
515 43517fcc Ermal LUÇI
	}
516
517 23a193da Phil Davis
	if (isset($config['system']['disablesegmentationoffloading'])) {
518 43517fcc Ermal LUÇI
		$flags_off |= IFCAP_TSO;
519 23a193da Phil Davis
	} else if (isset($options['caps']['tso']) || isset($options['caps']['tso4']) || isset($options['caps']['tso6'])) {
520 bc4d752b jim-p
		$flags_on |= IFCAP_TSO;
521 23a193da Phil Davis
	}
522 43517fcc Ermal LUÇI
523 bc4d752b jim-p
	if (isset($config['system']['disablelargereceiveoffloading'])) {
524 43517fcc Ermal LUÇI
		$flags_off |= IFCAP_LRO;
525 bc4d752b jim-p
	} else if (isset($options['caps']['lro'])) {
526 43517fcc Ermal LUÇI
		$flags_on |= IFCAP_LRO;
527 23a193da Phil Davis
	}
528 43517fcc Ermal LUÇI
529
	/* if the NIC supports polling *AND* it is enabled in the GUI */
530 bc4d752b jim-p
	if (!isset($config['system']['polling'])) {
531 43517fcc Ermal LUÇI
		$flags_off |= IFCAP_POLLING;
532 bc4d752b jim-p
	} else if (isset($options['caps']['polling'])) {
533 43517fcc Ermal LUÇI
		$flags_on |= IFCAP_POLLING;
534 23a193da Phil Davis
	}
535 43517fcc Ermal LUÇI
536
	pfSense_interface_capabilities($iface, -$flags_off);
537
	pfSense_interface_capabilities($iface, $flags_on);
538
}
539
540 3076becf Scott Ullrich
/****f* pfsense-utils/enable_hardware_offloading
541
 * NAME
542
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
543
 * INPUTS
544
 *   $interface	- string containing the physical interface to work on.
545
 * RESULT
546
 *   null
547
 * NOTES
548
 *   This function only supports the fxp driver's loadable microcode.
549
 ******/
550
function enable_hardware_offloading($interface) {
551
	global $g, $config;
552
553 a2934331 Scott Ullrich
	$int = get_real_interface($interface);
554 23a193da Phil Davis
	if (empty($int)) {
555 3d063391 Ermal
		return;
556 23a193da Phil Davis
	}
557 43517fcc Ermal LUÇI
558
	if (!isset($config['system']['do_not_use_nic_microcode'])) {
559
		/* translate wan, lan, opt -> real interface if needed */
560
		$int_family = preg_split("/[0-9]+/", $int);
561
		$supported_ints = array('fxp');
562
		if (in_array($int_family, $supported_ints)) {
563 23a193da Phil Davis
			if (does_interface_exist($int)) {
564 43517fcc Ermal LUÇI
				pfSense_interface_flags($int, IFF_LINK0);
565 23a193da Phil Davis
			}
566 43517fcc Ermal LUÇI
		}
567 a2934331 Scott Ullrich
	}
568 3076becf Scott Ullrich
569 43517fcc Ermal LUÇI
	/* This is mostly for vlans and ppp types */
570
	$realhwif = get_parent_interface($interface);
571 23a193da Phil Davis
	if ($realhwif[0] == $int) {
572 43517fcc Ermal LUÇI
		hardware_offloading_applyflags($int);
573 23a193da Phil Davis
	} else {
574 43517fcc Ermal LUÇI
		hardware_offloading_applyflags($realhwif[0]);
575
		hardware_offloading_applyflags($int);
576
	}
577 3076becf Scott Ullrich
}
578
579 f7eb54e4 Scott Ullrich
/****f* pfsense-utils/interface_supports_polling
580
 * NAME
581
 *   checks to see if an interface supports polling according to man polling
582
 * INPUTS
583
 *
584
 * RESULT
585
 *   true or false
586
 * NOTES
587
 *
588
 ******/
589
function interface_supports_polling($iface) {
590 3d063391 Ermal
	$opts = pfSense_get_interface_addresses($iface);
591 23a193da Phil Davis
	if (is_array($opts) && isset($opts['caps']['polling'])) {
592 f7eb54e4 Scott Ullrich
		return true;
593 23a193da Phil Davis
	}
594 3d063391 Ermal
595 f7eb54e4 Scott Ullrich
	return false;
596
}
597
598 3076becf Scott Ullrich
/****f* pfsense-utils/is_alias_inuse
599
 * NAME
600
 *   checks to see if an alias is currently in use by a rule
601
 * INPUTS
602
 *
603
 * RESULT
604
 *   true or false
605
 * NOTES
606
 *
607
 ******/
608
function is_alias_inuse($alias) {
609
	global $g, $config;
610
611 23a193da Phil Davis
	if ($alias == "") {
612
		return false;
613
	}
614 3076becf Scott Ullrich
	/* loop through firewall rules looking for alias in use */
615 23a193da Phil Davis
	if (is_array($config['filter']['rule'])) {
616
		foreach ($config['filter']['rule'] as $rule) {
617
			if ($rule['source']['address']) {
618
				if ($rule['source']['address'] == $alias) {
619 0c8c496e Scott Ullrich
					return true;
620 23a193da Phil Davis
				}
621
			}
622
			if ($rule['destination']['address']) {
623
				if ($rule['destination']['address'] == $alias) {
624 0c8c496e Scott Ullrich
					return true;
625 23a193da Phil Davis
				}
626
			}
627 0c8c496e Scott Ullrich
		}
628 23a193da Phil Davis
	}
629 3076becf Scott Ullrich
	/* loop through nat rules looking for alias in use */
630 23a193da Phil Davis
	if (is_array($config['nat']['rule'])) {
631
		foreach ($config['nat']['rule'] as $rule) {
632
			if ($rule['target'] && $rule['target'] == $alias) {
633 3076becf Scott Ullrich
				return true;
634 23a193da Phil Davis
			}
635
			if ($rule['source']['address'] && $rule['source']['address'] == $alias) {
636 59ecde49 Renato Botelho
				return true;
637 23a193da Phil Davis
			}
638
			if ($rule['destination']['address'] && $rule['destination']['address'] == $alias) {
639 3076becf Scott Ullrich
				return true;
640 23a193da Phil Davis
			}
641 3076becf Scott Ullrich
		}
642 23a193da Phil Davis
	}
643 3076becf Scott Ullrich
	return false;
644
}
645
646 63724b02 Scott Dale
/****f* pfsense-utils/is_schedule_inuse
647
 * NAME
648
 *   checks to see if a schedule is currently in use by a rule
649
 * INPUTS
650
 *
651
 * RESULT
652
 *   true or false
653
 * NOTES
654
 *
655
 ******/
656
function is_schedule_inuse($schedule) {
657
	global $g, $config;
658
659 23a193da Phil Davis
	if ($schedule == "") {
660
		return false;
661
	}
662 63724b02 Scott Dale
	/* loop through firewall rules looking for schedule in use */
663 23a193da Phil Davis
	if (is_array($config['filter']['rule'])) {
664
		foreach ($config['filter']['rule'] as $rule) {
665
			if ($rule['sched'] == $schedule) {
666 591ceb32 Scott Dale
				return true;
667 23a193da Phil Davis
			}
668 63724b02 Scott Dale
		}
669 23a193da Phil Davis
	}
670 63724b02 Scott Dale
	return false;
671
}
672
673 3076becf Scott Ullrich
/****f* pfsense-utils/setup_polling
674
 * NAME
675
 *   sets up polling
676
 * INPUTS
677
 *
678
 * RESULT
679
 *   null
680
 * NOTES
681
 *
682
 ******/
683
function setup_polling() {
684
	global $g, $config;
685
686 23a193da Phil Davis
	if (isset($config['system']['polling'])) {
687 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.idle_poll", "1");
688 23a193da Phil Davis
	} else {
689 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.idle_poll", "0");
690 23a193da Phil Davis
	}
691 3076becf Scott Ullrich
692 23a193da Phil Davis
	if ($config['system']['polling_each_burst']) {
693 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.each_burst", $config['system']['polling_each_burst']);
694 23a193da Phil Davis
	}
695
	if ($config['system']['polling_burst_max']) {
696 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.burst_max", $config['system']['polling_burst_max']);
697 23a193da Phil Davis
	}
698
	if ($config['system']['polling_user_frac']) {
699 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.user_frac", $config['system']['polling_user_frac']);
700 23a193da Phil Davis
	}
701 3076becf Scott Ullrich
}
702
703
/****f* pfsense-utils/setup_microcode
704
 * NAME
705
 *   enumerates all interfaces and calls enable_hardware_offloading which
706
 *   enables a NIC's supported hardware features.
707
 * INPUTS
708
 *
709
 * RESULT
710
 *   null
711
 * NOTES
712
 *   This function only supports the fxp driver's loadable microcode.
713
 ******/
714
function setup_microcode() {
715
716 3a4ce87d Ermal Luçi
	/* if list */
717 43517fcc Ermal LUÇI
	$iflist = get_configured_interface_list(false, true);
718 23a193da Phil Davis
	foreach ($iflist as $if => $ifdescr) {
719 3076becf Scott Ullrich
		enable_hardware_offloading($if);
720 23a193da Phil Davis
	}
721 dced0dd0 Ermal LUÇI
	unset($iflist);
722 3076becf Scott Ullrich
}
723
724
/****f* pfsense-utils/get_carp_status
725
 * NAME
726
 *   get_carp_status - Return whether CARP is enabled or disabled.
727
 * RESULT
728
 *   boolean	- true if CARP is enabled, false if otherwise.
729
 ******/
730
function get_carp_status() {
731 5fa78adc Renato Botelho
	/* grab the current status of carp */
732 971de1f9 Renato Botelho
	$status = get_single_sysctl('net.inet.carp.allow');
733 5fa78adc Renato Botelho
	return (intval($status) > 0);
734 3076becf Scott Ullrich
}
735
736
/*
737
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
738 52947718 Ermal Lu?i
739 3076becf Scott Ullrich
 */
740
function convert_ip_to_network_format($ip, $subnet) {
741 2ce660ad smos
	$ipsplit = explode('.', $ip);
742 3076becf Scott Ullrich
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
743
	return $string;
744
}
745
746
/*
747 2a0aef55 Luiz Otavio O Souza
 * get_carp_interface_status($carpid): returns the status of a carp uniqid
748 3076becf Scott Ullrich
 */
749 2a0aef55 Luiz Otavio O Souza
function get_carp_interface_status($carpid) {
750
751
	$carpiface = get_configured_vip_interface($carpid);
752
	if ($carpiface == NULL)
753
		return "";
754
	$interface = get_real_interface($carpiface);
755
	if ($interface == NULL)
756
		return "";
757 5ad69855 Fredrik Rönnvall
	$vip = get_configured_vip($carpid);
758
	if ($vip == NULL || !isset($vip['vhid']))
759
		return "";
760 2a0aef55 Luiz Otavio O Souza
761 5ad69855 Fredrik Rönnvall
	$vhid = $vip['vhid'];
762 2a0aef55 Luiz Otavio O Souza
	$carp_query = '';
763 8cb09b29 jim-p
	$_gb = exec("/sbin/ifconfig {$interface} | /usr/bin/grep \"carp:.* vhid {$vhid} \"", $carp_query);
764 2a0aef55 Luiz Otavio O Souza
	foreach ($carp_query as $int) {
765
		if (stripos($int, "MASTER"))
766
			return "MASTER";
767
		elseif (stripos($int, "BACKUP"))
768
			return "BACKUP";
769
		elseif (stripos($int, "INIT"))
770
			return "INIT";
771 3076becf Scott Ullrich
	}
772 e686a73f Luiz Otavio O Souza
773 0f98065b Luiz Otavio O Souza
	return "";
774 3076becf Scott Ullrich
}
775
776
/*
777
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
778
 */
779
function get_pfsync_interface_status($pfsyncinterface) {
780 23a193da Phil Davis
	if (!does_interface_exist($pfsyncinterface)) {
781 306f8556 Renato Botelho
		return;
782 23a193da Phil Davis
	}
783 306f8556 Renato Botelho
784
	return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
785 3076becf Scott Ullrich
}
786
787
/*
788
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
789
 */
790
function add_rule_to_anchor($anchor, $rule, $label) {
791 873c1701 Renato Botelho
	mwexec("echo " . escapeshellarg($rule) . " | /sbin/pfctl -a " . escapeshellarg($anchor) . ":" . escapeshellarg($label) . " -f -");
792 3076becf Scott Ullrich
}
793
794
/*
795
 * remove_text_from_file
796
 * remove $text from file $file
797
 */
798
function remove_text_from_file($file, $text) {
799 23a193da Phil Davis
	if (!file_exists($file) && !is_writable($file)) {
800 2addd5b2 Ermal
		return;
801 23a193da Phil Davis
	}
802 3076becf Scott Ullrich
	$filecontents = file_get_contents($file);
803 2addd5b2 Ermal
	$text = str_replace($text, "", $filecontents);
804 5fa78adc Renato Botelho
	@file_put_contents($file, $text);
805 3076becf Scott Ullrich
}
806
807
/*
808
 *   after_sync_bump_adv_skew(): create skew values by 1S
809
 */
810
function after_sync_bump_adv_skew() {
811
	global $config, $g;
812
	$processed_skew = 1;
813
	$a_vip = &$config['virtualip']['vip'];
814
	foreach ($a_vip as $vipent) {
815 23a193da Phil Davis
		if ($vipent['advskew'] <> "") {
816 3076becf Scott Ullrich
			$processed_skew = 1;
817
			$vipent['advskew'] = $vipent['advskew']+1;
818
		}
819
	}
820 23a193da Phil Davis
	if ($processed_skew == 1) {
821 7d1b238c Carlos Eduardo Ramos
		write_config(gettext("After synch increase advertising skew"));
822 23a193da Phil Davis
	}
823 3076becf Scott Ullrich
}
824
825
/*
826
 * get_filename_from_url($url): converts a url to its filename.
827
 */
828
function get_filename_from_url($url) {
829
	return basename($url);
830
}
831
832
/*
833
 *   get_dir: return an array of $dir
834
 */
835
function get_dir($dir) {
836
	$dir_array = array();
837
	$d = dir($dir);
838 9488f42b Phil Davis
	if (!is_object($d)) {
839 68cf7ccb NewEraCracker
		return array();
840
	}
841 3076becf Scott Ullrich
	while (false !== ($entry = $d->read())) {
842
		array_push($dir_array, $entry);
843
	}
844
	$d->close();
845
	return $dir_array;
846
}
847
848
/****f* pfsense-utils/WakeOnLan
849
 * NAME
850
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
851
 * RESULT
852
 *   true/false - true if the operation was successful
853
 ******/
854 086cf944 Phil Davis
function WakeOnLan($addr, $mac) {
855 3076becf Scott Ullrich
	$addr_byte = explode(':', $mac);
856
	$hw_addr = '';
857
858 4de8f7ba Phil Davis
	for ($a = 0; $a < 6; $a++) {
859 3076becf Scott Ullrich
		$hw_addr .= chr(hexdec($addr_byte[$a]));
860 23a193da Phil Davis
	}
861 3076becf Scott Ullrich
862
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
863
864 23a193da Phil Davis
	for ($a = 1; $a <= 16; $a++) {
865 3076becf Scott Ullrich
		$msg .= $hw_addr;
866 23a193da Phil Davis
	}
867 3076becf Scott Ullrich
868
	// send it to the broadcast address using UDP
869
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
870
	if ($s == false) {
871 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Error creating socket!"));
872 addc0439 Renato Botelho
		log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), socket_last_error($s), socket_strerror(socket_last_error($s))));
873 3076becf Scott Ullrich
	} else {
874
		// setting a broadcast option to socket:
875 4de8f7ba Phil Davis
		$opt_ret = socket_set_option($s, 1, 6, TRUE);
876 23a193da Phil Davis
		if ($opt_ret < 0) {
877 7d1b238c Carlos Eduardo Ramos
			log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret)));
878 23a193da Phil Davis
		}
879 3076becf Scott Ullrich
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
880
		socket_close($s);
881 e8c516a0 Phil Davis
		log_error(sprintf(gettext('Magic Packet sent (%1$s) to (%2$s) MAC=%3$s'), $e, $addr, $mac));
882 3076becf Scott Ullrich
		return true;
883 0c8c496e Scott Ullrich
	}
884 3076becf Scott Ullrich
885
	return false;
886
}
887
888
/*
889
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
890
 *					 Useful for finding paths and stripping file extensions.
891
 */
892
function reverse_strrchr($haystack, $needle) {
893 23a193da Phil Davis
	if (!is_string($haystack)) {
894 4824d857 Ermal Lu?i
		return;
895 23a193da Phil Davis
	}
896
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1) : false;
897 3076becf Scott Ullrich
}
898
899
/*
900
 *  backup_config_section($section): returns as an xml file string of
901
 *                                   the configuration section
902
 */
903 8dcca9b5 Darren Embry
function backup_config_section($section_name) {
904 3076becf Scott Ullrich
	global $config;
905 8dcca9b5 Darren Embry
	$new_section = &$config[$section_name];
906 3076becf Scott Ullrich
	/* generate configuration XML */
907 8dcca9b5 Darren Embry
	$xmlconfig = dump_xml_config($new_section, $section_name);
908 3076becf Scott Ullrich
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
909
	return $xmlconfig;
910
}
911
912
/*
913 8dcca9b5 Darren Embry
 *  restore_config_section($section_name, new_contents): restore a configuration section,
914 3076becf Scott Ullrich
 *                                                  and write the configuration out
915
 *                                                  to disk/cf.
916
 */
917 8dcca9b5 Darren Embry
function restore_config_section($section_name, $new_contents) {
918 3076becf Scott Ullrich
	global $config, $g;
919
	conf_mount_rw();
920 4de8f7ba Phil Davis
	$fout = fopen("{$g['tmp_path']}/tmpxml", "w");
921 3076becf Scott Ullrich
	fwrite($fout, $new_contents);
922
	fclose($fout);
923 8dcca9b5 Darren Embry
924
	$xml = parse_xml_config($g['tmp_path'] . "/tmpxml", null);
925
	if ($xml['pfsense']) {
926
		$xml = $xml['pfsense'];
927
	}
928
	else if ($xml['m0n0wall']) {
929
		$xml = $xml['m0n0wall'];
930
	}
931
	if ($xml[$section_name]) {
932
		$section_xml = $xml[$section_name];
933
	} else {
934
		$section_xml = -1;
935
	}
936
937 541989d5 Ermal
	@unlink($g['tmp_path'] . "/tmpxml");
938 8dcca9b5 Darren Embry
	if ($section_xml === -1) {
939
		return false;
940
	}
941
	$config[$section_name] = &$section_xml;
942 23a193da Phil Davis
	if (file_exists("{$g['tmp_path']}/config.cache")) {
943 a57d6170 Scott Ullrich
		unlink("{$g['tmp_path']}/config.cache");
944 23a193da Phil Davis
	}
945 8dcca9b5 Darren Embry
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
946 0f806eca Erik Fonnesbeck
	disable_security_checks();
947 3076becf Scott Ullrich
	conf_mount_ro();
948 8dcca9b5 Darren Embry
	return true;
949 3076becf Scott Ullrich
}
950
951
/*
952 8dcca9b5 Darren Embry
 *  merge_config_section($section_name, new_contents):   restore a configuration section,
953 3076becf Scott Ullrich
 *                                                  and write the configuration out
954
 *                                                  to disk/cf.  But preserve the prior
955
 * 													structure if needed
956
 */
957 8dcca9b5 Darren Embry
function merge_config_section($section_name, $new_contents) {
958 3076becf Scott Ullrich
	global $config;
959
	conf_mount_rw();
960
	$fname = get_tmp_filename();
961
	$fout = fopen($fname, "w");
962
	fwrite($fout, $new_contents);
963
	fclose($fout);
964 8dcca9b5 Darren Embry
	$section_xml = parse_xml_config($fname, $section_name);
965
	$config[$section_name] = $section_xml;
966 3076becf Scott Ullrich
	unlink($fname);
967 8dcca9b5 Darren Embry
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
968 0f806eca Erik Fonnesbeck
	disable_security_checks();
969 3076becf Scott Ullrich
	conf_mount_ro();
970
	return;
971
}
972
973
/*
974 4de8f7ba Phil Davis
 * rmdir_recursive($path, $follow_links=false)
975 3076becf Scott Ullrich
 * Recursively remove a directory tree (rm -rf path)
976
 * This is for directories _only_
977
 */
978 4de8f7ba Phil Davis
function rmdir_recursive($path, $follow_links=false) {
979 3076becf Scott Ullrich
	$to_do = glob($path);
980 23a193da Phil Davis
	if (!is_array($to_do)) {
981
		$to_do = array($to_do);
982
	}
983
	foreach ($to_do as $workingdir) { // Handle wildcards by foreaching.
984
		if (file_exists($workingdir)) {
985
			if (is_dir($workingdir)) {
986 3076becf Scott Ullrich
				$dir = opendir($workingdir);
987
				while ($entry = readdir($dir)) {
988 23a193da Phil Davis
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry"))) {
989 3076becf Scott Ullrich
						unlink("$workingdir/$entry");
990 4de8f7ba Phil Davis
					} elseif (is_dir("$workingdir/$entry") && $entry != '.' && $entry != '..') {
991 3076becf Scott Ullrich
						rmdir_recursive("$workingdir/$entry");
992 23a193da Phil Davis
					}
993 6613a031 Scott Ullrich
				}
994 3076becf Scott Ullrich
				closedir($dir);
995
				rmdir($workingdir);
996
			} elseif (is_file($workingdir)) {
997
				unlink($workingdir);
998
			}
999 5fa78adc Renato Botelho
		}
1000 3076becf Scott Ullrich
	}
1001
	return;
1002
}
1003
1004 e501de37 Ermal
/*
1005
 * host_firmware_version(): Return the versions used in this install
1006
 */
1007 18be996d Ermal
function host_firmware_version($tocheck = "") {
1008 5fa78adc Renato Botelho
	global $g, $config;
1009 e501de37 Ermal
1010 02406801 jim-p
	$os_version = trim(substr(php_uname("r"), 0, strpos(php_uname("r"), '-')));
1011
1012 5fa78adc Renato Botelho
	return array(
1013 5779ade6 Renato Botelho
		"firmware" => array("version" => $g['product_version']),
1014 02406801 jim-p
		"kernel"   => array("version" => $os_version),
1015
		"base"     => array("version" => $os_version),
1016 5fa78adc Renato Botelho
		"platform" => trim(file_get_contents('/etc/platform', " \n")),
1017
		"config_version" => $config['version']
1018
	);
1019 e501de37 Ermal
}
1020
1021 3076becf Scott Ullrich
function get_disk_info() {
1022
	$diskout = "";
1023
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
1024
	return explode(' ', $diskout[0]);
1025
}
1026
1027
/****f* pfsense-utils/strncpy
1028
 * NAME
1029
 *   strncpy - copy strings
1030
 * INPUTS
1031
 *   &$dst, $src, $length
1032
 * RESULT
1033
 *   none
1034
 ******/
1035
function strncpy(&$dst, $src, $length) {
1036
	if (strlen($src) > $length) {
1037
		$dst = substr($src, 0, $length);
1038
	} else {
1039
		$dst = $src;
1040
	}
1041
}
1042
1043
/****f* pfsense-utils/reload_interfaces_sync
1044
 * NAME
1045
 *   reload_interfaces - reload all interfaces
1046
 * INPUTS
1047
 *   none
1048
 * RESULT
1049
 *   none
1050
 ******/
1051
function reload_interfaces_sync() {
1052 c0836064 Ermal Luçi
	global $config, $g;
1053 3076becf Scott Ullrich
1054 23a193da Phil Davis
	if ($g['debug']) {
1055 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("reload_interfaces_sync() is starting."));
1056 23a193da Phil Davis
	}
1057 3076becf Scott Ullrich
1058
	/* parse config.xml again */
1059
	$config = parse_config(true);
1060
1061 a5d6f60b Ermal Lu?i
	/* enable routing */
1062
	system_routing_enable();
1063 23a193da Phil Davis
	if ($g['debug']) {
1064 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Enabling system routing"));
1065 23a193da Phil Davis
	}
1066 3076becf Scott Ullrich
1067 23a193da Phil Davis
	if ($g['debug']) {
1068 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Cleaning up Interfaces"));
1069 23a193da Phil Davis
	}
1070 3076becf Scott Ullrich
1071 67ee1ec5 Ermal Luçi
	/* set up interfaces */
1072
	interfaces_configure();
1073 3076becf Scott Ullrich
}
1074
1075
/****f* pfsense-utils/reload_all
1076
 * NAME
1077
 *   reload_all - triggers a reload of all settings
1078
 *   * INPUTS
1079
 *   none
1080
 * RESULT
1081
 *   none
1082
 ******/
1083
function reload_all() {
1084 0ae6daf8 Ermal
	send_event("service reload all");
1085 3076becf Scott Ullrich
}
1086
1087
/****f* pfsense-utils/reload_interfaces
1088
 * NAME
1089
 *   reload_interfaces - triggers a reload of all interfaces
1090
 * INPUTS
1091
 *   none
1092
 * RESULT
1093
 *   none
1094
 ******/
1095
function reload_interfaces() {
1096 5e3a84e2 Ermal
	send_event("interface all reload");
1097 3076becf Scott Ullrich
}
1098
1099
/****f* pfsense-utils/reload_all_sync
1100
 * NAME
1101
 *   reload_all - reload all settings
1102
 *   * INPUTS
1103
 *   none
1104
 * RESULT
1105
 *   none
1106
 ******/
1107
function reload_all_sync() {
1108
	global $config, $g;
1109
1110
	/* parse config.xml again */
1111
	$config = parse_config(true);
1112
1113
	/* set up our timezone */
1114
	system_timezone_configure();
1115
1116
	/* set up our hostname */
1117
	system_hostname_configure();
1118
1119
	/* make hosts file */
1120
	system_hosts_generate();
1121
1122
	/* generate resolv.conf */
1123
	system_resolvconf_generate();
1124
1125
	/* enable routing */
1126
	system_routing_enable();
1127
1128 a5d6f60b Ermal Lu?i
	/* set up interfaces */
1129
	interfaces_configure();
1130 3076becf Scott Ullrich
1131
	/* start dyndns service */
1132
	services_dyndns_configure();
1133
1134
	/* configure cron service */
1135
	configure_cron();
1136
1137
	/* start the NTP client */
1138
	system_ntp_configure();
1139
1140
	/* sync pw database */
1141
	conf_mount_rw();
1142 6b0c5879 Scott Ullrich
	unlink_if_exists("/etc/spwd.db.tmp");
1143 3076becf Scott Ullrich
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1144
	conf_mount_ro();
1145
1146
	/* restart sshd */
1147 0ae6daf8 Ermal
	send_event("service restart sshd");
1148 3076becf Scott Ullrich
1149
	/* restart webConfigurator if needed */
1150 0ae6daf8 Ermal
	send_event("service restart webgui");
1151 3076becf Scott Ullrich
}
1152
1153 4de8f7ba Phil Davis
function setup_serial_port($when = "save", $path = "") {
1154 3076becf Scott Ullrich
	global $g, $config;
1155
	conf_mount_rw();
1156 02e4ee54 Renato Botelho
	$ttys_file = "{$path}/etc/ttys";
1157 196d0085 jim-p
	$boot_config_file = "{$path}/boot.config";
1158
	$loader_conf_file = "{$path}/boot/loader.conf";
1159 3076becf Scott Ullrich
	/* serial console - write out /boot.config */
1160 23a193da Phil Davis
	if (file_exists($boot_config_file)) {
1161 196d0085 jim-p
		$boot_config = file_get_contents($boot_config_file);
1162 23a193da Phil Davis
	} else {
1163 3076becf Scott Ullrich
		$boot_config = "";
1164 23a193da Phil Davis
	}
1165 3076becf Scott Ullrich
1166 4887afa1 Renato Botelho
	$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "115200";
1167 38c7d42e Renato Botelho
	if ($g['platform'] != "cdrom") {
1168 986e77a2 Renato Botelho
		$serial_only = false;
1169 57c616e2 Renato Botelho
		$vga_only = false;
1170
1171
		$specific_platform = system_identify_specific_platform();
1172 986e77a2 Renato Botelho
1173 03b56525 Renato Botelho
		if (($g['platform'] == "nanobsd") && isset($g['enableserial_force'])) {
1174 986e77a2 Renato Botelho
			$serial_only = true;
1175 f962a59a Renato Botelho
		} elseif ($specific_platform['name'] ==  'XG-1540') {
1176 57c616e2 Renato Botelho
			$vga_only = true;
1177
		} elseif ($specific_platform['name'] == 'RCC-VE' ||
1178
		    $specific_platform['name'] == 'RCC' ||
1179
		    $specific_platform['name'] == 'RCC-DFF' ||
1180
		    $specific_platform['name'] == 'apu2') {
1181
			$serial_only = true;
1182 986e77a2 Renato Botelho
		}
1183
1184 cfbfd941 smos
		$boot_config_split = explode("\n", $boot_config);
1185 4e3bf4aa Renato Botelho
		$data = array();
1186
		foreach ($boot_config_split as $bcs) {
1187
			/* Ignore -D and -h lines now */
1188
			if (!empty($bcs) && !stristr($bcs, "-D") &&
1189
			    !stristr($bcs, "-h")) {
1190
				$data[] = $bcs;
1191 0c8c496e Scott Ullrich
			}
1192 4e3bf4aa Renato Botelho
		}
1193
		if ($serial_only === true) {
1194
			$data[] = "-S{$serialspeed} -h";
1195
		} elseif (is_serial_enabled()) {
1196
			$data[] = "-S{$serialspeed} -D";
1197
		}
1198
1199
		if (empty($data)) {
1200
			@unlink($boot_conf_file);
1201
		} else {
1202
			safe_write_file($boot_config_file, $data);
1203 0c8c496e Scott Ullrich
		}
1204 38c7d42e Renato Botelho
1205 4e3bf4aa Renato Botelho
		unset($boot_config, $boot_config_file, $boot_config_split);
1206
1207 3076becf Scott Ullrich
		/* serial console - write out /boot/loader.conf */
1208 23a193da Phil Davis
		if ($when == "upgrade") {
1209 baef6be8 jim-p
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
1210 23a193da Phil Davis
		}
1211 5f36c658 jim-p
1212 4e3bf4aa Renato Botelho
		$loader_conf = file_get_contents($loader_conf_file);
1213
		$loader_conf_split = explode("\n", $loader_conf);
1214
1215
		$data = array();
1216
		// Loop through and only add lines that are not empty, and which
1217
		//  do not contain a console directive.
1218
		foreach ($loader_conf_split as $bcs) {
1219
			if (!empty($bcs) &&
1220
			    (stripos($bcs, "console") === false) &&
1221
			    (stripos($bcs, "boot_multicons") === false) &&
1222
			    (stripos($bcs, "boot_serial") === false) &&
1223
			    (stripos($bcs, "hw.usb.no_pf") === false) &&
1224
			    (stripos($bcs, "hint.uart.0.flags") === false) &&
1225
			    (stripos($bcs, "hint.uart.1.flags") === false)) {
1226
				$data[] = $bcs;
1227 ba79655c Chris Buechler
			}
1228 4e3bf4aa Renato Botelho
		}
1229 25c088de Renato Botelho
1230 4e3bf4aa Renato Botelho
		if ($serial_only === true) {
1231
			$data[] = 'boot_serial="YES"';
1232
			$data[] = 'console="comconsole"';
1233 57c616e2 Renato Botelho
		} elseif ($vga_only === true) {
1234
			$data[] = 'console="vidconsole"';
1235
		} elseif (is_serial_enabled()) {
1236 4e3bf4aa Renato Botelho
			$data[] = 'boot_multicons="YES"';
1237
			$data[] = 'boot_serial="YES"';
1238
			$primaryconsole = isset($g['primaryconsole_force']) ?
1239
			    $g['primaryconsole_force'] :
1240
			    $config['system']['primaryconsole'];
1241
			switch ($primaryconsole) {
1242
				case "video":
1243
					$data[] = 'console="vidconsole,comconsole"';
1244
					break;
1245
				case "serial":
1246
				default:
1247
					$data[] = 'console="comconsole,vidconsole"';
1248
			}
1249
		}
1250
		$data[] = 'comconsole_speed="' . $serialspeed . '"';
1251
1252 57c616e2 Renato Botelho
		if ($specific_platform['name'] == 'RCC-VE' ||
1253
		    $specific_platform['name'] == 'RCC' ||
1254
		    $specific_platform['name'] == 'RCC-DFF') {
1255 4e3bf4aa Renato Botelho
			$data[] = 'comconsole_port="0x2F8"';
1256
			$data[] = 'hint.uart.0.flags="0x00"';
1257
			$data[] = 'hint.uart.1.flags="0x10"';
1258 0c8c496e Scott Ullrich
		}
1259 4e3bf4aa Renato Botelho
		$data[] = 'hw.usb.no_pf="1"';
1260
1261
		safe_write_file($loader_conf_file, $data);
1262
1263
		unset($loader_conf, $loader_conf_split, $loader_config_file);
1264 0c8c496e Scott Ullrich
	}
1265 4e3bf4aa Renato Botelho
1266 02e4ee54 Renato Botelho
	$ttys = file_get_contents($ttys_file);
1267 cfbfd941 smos
	$ttys_split = explode("\n", $ttys);
1268 4e3bf4aa Renato Botelho
1269
	$data = array();
1270 c5f9fb72 Renato Botelho
1271 4f009171 Renato Botelho
	$on_off = (is_serial_enabled() ? 'onifconsole' : 'off');
1272 c5f9fb72 Renato Botelho
1273 edb4b657 Renato Botelho
	if (isset($config['system']['disableconsolemenu'])) {
1274
		$console_type = 'Pc';
1275
		$serial_type = 'std.' . $serialspeed;
1276
	} else {
1277
		$console_type = 'al.Pc';
1278
		$serial_type = 'al.' . $serialspeed;
1279
	}
1280 7fa3bcae Renato Botelho
1281 4e3bf4aa Renato Botelho
	$console_line = "console\tnone\t\t\t\tunknown\toff\tsecure";
1282
	$ttyv0_line =
1283
	    "ttyv0\t\"/usr/libexec/getty {$console_type}\"\tcons25\ton\tsecure";
1284
	$ttyu_line =
1285
	    "\"/usr/libexec/getty {$serial_type}\"\tcons25\t{$on_off}\tsecure";
1286 7fa3bcae Renato Botelho
1287
	$found = array();
1288
1289 23a193da Phil Davis
	foreach ($ttys_split as $tty) {
1290 4e3bf4aa Renato Botelho
		/* Ignore blank lines */
1291
		if (empty($tty)) {
1292
			continue;
1293
		}
1294
1295 23a193da Phil Davis
		if (stristr($tty, "ttyv0")) {
1296 7fa3bcae Renato Botelho
			$found['ttyv0'] = 1;
1297 4e3bf4aa Renato Botelho
			$data[] = $ttyv0_line;
1298 7fa3bcae Renato Botelho
		} elseif (stristr($tty, "ttyu")) {
1299 4f009171 Renato Botelho
			$ttyn = substr($tty, 0, 5);
1300 7fa3bcae Renato Botelho
			$found[$ttyn] = 1;
1301 4e3bf4aa Renato Botelho
			$data[] = "{$ttyn}\t{$ttyu_line}";
1302 7fa3bcae Renato Botelho
		} elseif (substr($tty, 0, 7) == 'console') {
1303
			$found['console'] = 1;
1304 4e3bf4aa Renato Botelho
			$data[] = $tty;
1305 23a193da Phil Davis
		} else {
1306 4e3bf4aa Renato Botelho
			$data[] = $tty;
1307 23a193da Phil Davis
		}
1308 3076becf Scott Ullrich
	}
1309 edb4b657 Renato Botelho
	unset($on_off, $console_type, $serial_type);
1310 7fa3bcae Renato Botelho
1311
	/* Detect missing main lines on original file and try to rebuild it */
1312
	$items = array(
1313
		'console',
1314
		'ttyv0',
1315
		'ttyu0',
1316
		'ttyu1',
1317
		'ttyu2',
1318
		'ttyu3'
1319
	);
1320
1321
	foreach ($items as $item) {
1322
		if (isset($found[$item])) {
1323
			continue;
1324
		}
1325
1326
		if ($item == 'console') {
1327 4e3bf4aa Renato Botelho
			$data[] = $console_line;
1328 7fa3bcae Renato Botelho
		} elseif ($item == 'ttyv0') {
1329 4e3bf4aa Renato Botelho
			$data[] = $ttyv0_line;
1330 7fa3bcae Renato Botelho
		} else {
1331 4e3bf4aa Renato Botelho
			$data[] = "{$item}\t{$ttyu_line}";
1332 7fa3bcae Renato Botelho
		}
1333
	}
1334
1335 4e3bf4aa Renato Botelho
	safe_write_file($ttys_file, $data);
1336
1337
	unset($ttys, $ttys_file, $ttys_split, $data);
1338
1339 23a193da Phil Davis
	if ($when != "upgrade") {
1340 02e4ee54 Renato Botelho
		reload_ttys();
1341 23a193da Phil Davis
	}
1342 a46e450c Ermal Lu?i
1343 3076becf Scott Ullrich
	conf_mount_ro();
1344
	return;
1345
}
1346
1347 38c7d42e Renato Botelho
function is_serial_enabled() {
1348
	global $g, $config;
1349
1350
	if (!isset($g['enableserial_force']) &&
1351
	    !isset($config['system']['enableserial']) &&
1352 2344bed4 Renato Botelho
	    ($g['platform'] == $g['product_name'] || $g['platform'] == "cdrom")) {
1353 38c7d42e Renato Botelho
		return false;
1354 23a193da Phil Davis
	}
1355 38c7d42e Renato Botelho
1356
	return true;
1357
}
1358
1359 edb4b657 Renato Botelho
function reload_ttys() {
1360
	// Send a HUP signal to init will make it reload /etc/ttys
1361
	posix_kill(1, SIGHUP);
1362
}
1363
1364 3076becf Scott Ullrich
function print_value_list($list, $count = 10, $separator = ",") {
1365
	$list = implode($separator, array_slice($list, 0, $count));
1366 23a193da Phil Davis
	if (count($list) < $count) {
1367 3076becf Scott Ullrich
		$list .= ".";
1368
	} else {
1369
		$list .= "...";
1370
	}
1371
	return $list;
1372
}
1373
1374 bfe776f0 Ermal Luçi
/* DHCP enabled on any interfaces? */
1375 abdd01f5 Ermal
function is_dhcp_server_enabled() {
1376 db9fabf3 Ermal Luçi
	global $config;
1377 bfe776f0 Ermal Luçi
1378 23a193da Phil Davis
	if (!is_array($config['dhcpd'])) {
1379 bfe776f0 Ermal Luçi
		return false;
1380 23a193da Phil Davis
	}
1381 bfe776f0 Ermal Luçi
1382 abdd01f5 Ermal
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1383 23a193da Phil Davis
		if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif])) {
1384 abdd01f5 Ermal
			return true;
1385 23a193da Phil Davis
		}
1386 3076becf Scott Ullrich
	}
1387 bfe776f0 Ermal Luçi
1388 abdd01f5 Ermal
	return false;
1389 a6610d82 smos
}
1390
1391
/* DHCP enabled on any interfaces? */
1392 abdd01f5 Ermal
function is_dhcpv6_server_enabled() {
1393 a6610d82 smos
	global $config;
1394
1395 abdd01f5 Ermal
	if (is_array($config['interfaces'])) {
1396
		foreach ($config['interfaces'] as $ifcfg) {
1397 23a193da Phil Davis
			if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface'])) {
1398 abdd01f5 Ermal
				return true;
1399 23a193da Phil Davis
			}
1400 a6610d82 smos
		}
1401
	}
1402
1403 23a193da Phil Davis
	if (!is_array($config['dhcpdv6'])) {
1404 a6610d82 smos
		return false;
1405 23a193da Phil Davis
	}
1406 a6610d82 smos
1407 abdd01f5 Ermal
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1408 23a193da Phil Davis
		if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if])) {
1409 abdd01f5 Ermal
			return true;
1410 23a193da Phil Davis
		}
1411 65b1e7d5 Seth Mos
	}
1412
1413 abdd01f5 Ermal
	return false;
1414 3076becf Scott Ullrich
}
1415
1416 0ed8d746 bcyrill
/* radvd enabled on any interfaces? */
1417
function is_radvd_enabled() {
1418
	global $config;
1419
1420 23a193da Phil Davis
	if (!is_array($config['dhcpdv6'])) {
1421 0ed8d746 bcyrill
		$config['dhcpdv6'] = array();
1422 23a193da Phil Davis
	}
1423 0ed8d746 bcyrill
1424
	$dhcpdv6cfg = $config['dhcpdv6'];
1425
	$Iflist = get_configured_interface_list();
1426
1427
	/* handle manually configured DHCP6 server settings first */
1428
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1429 23a193da Phil Davis
		if (!isset($config['interfaces'][$dhcpv6if]['enable'])) {
1430 0ed8d746 bcyrill
			continue;
1431 23a193da Phil Davis
		}
1432 0ed8d746 bcyrill
1433 23a193da Phil Davis
		if (!isset($dhcpv6ifconf['ramode'])) {
1434 0ed8d746 bcyrill
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1435 23a193da Phil Davis
		}
1436 0ed8d746 bcyrill
1437 23a193da Phil Davis
		if ($dhcpv6ifconf['ramode'] == "disabled") {
1438 0ed8d746 bcyrill
			continue;
1439 23a193da Phil Davis
		}
1440 0ed8d746 bcyrill
1441
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1442 23a193da Phil Davis
		if (!is_ipaddrv6($ifcfgipv6)) {
1443 0ed8d746 bcyrill
			continue;
1444 23a193da Phil Davis
		}
1445 0ed8d746 bcyrill
1446
		return true;
1447
	}
1448
1449
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1450
	foreach ($Iflist as $if => $ifdescr) {
1451 23a193da Phil Davis
		if (!isset($config['interfaces'][$if]['track6-interface'])) {
1452 0ed8d746 bcyrill
			continue;
1453 23a193da Phil Davis
		}
1454
		if (!isset($config['interfaces'][$if]['enable'])) {
1455 0ed8d746 bcyrill
			continue;
1456 23a193da Phil Davis
		}
1457 0ed8d746 bcyrill
1458
		$ifcfgipv6 = get_interface_ipv6($if);
1459 23a193da Phil Davis
		if (!is_ipaddrv6($ifcfgipv6)) {
1460 0ed8d746 bcyrill
			continue;
1461 23a193da Phil Davis
		}
1462 0ed8d746 bcyrill
1463
		$ifcfgsnv6 = get_interface_subnetv6($if);
1464
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1465
1466 23a193da Phil Davis
		if (!is_ipaddrv6($subnetv6)) {
1467 0ed8d746 bcyrill
			continue;
1468 23a193da Phil Davis
		}
1469 0ed8d746 bcyrill
1470
		return true;
1471
	}
1472
1473
	return false;
1474
}
1475
1476 93c2c1e6 jim-p
/* Any PPPoE servers enabled? */
1477
function is_pppoe_server_enabled() {
1478
	global $config;
1479
1480
	$pppoeenable = false;
1481
1482 23a193da Phil Davis
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe'])) {
1483 93c2c1e6 jim-p
		return false;
1484 23a193da Phil Davis
	}
1485 93c2c1e6 jim-p
1486 23a193da Phil Davis
	foreach ($config['pppoes']['pppoe'] as $pppoes) {
1487
		if ($pppoes['mode'] == 'server') {
1488 93c2c1e6 jim-p
			$pppoeenable = true;
1489 23a193da Phil Davis
		}
1490
	}
1491 93c2c1e6 jim-p
1492
	return $pppoeenable;
1493
}
1494
1495 fedbe5af stilez
/* Optional arg forces hh:mm:ss without days */
1496
function convert_seconds_to_dhms($sec, $showhoursonly = false) {
1497 8c91c89f stilez
	if (!is_numericint($sec)) {
1498
		return '-';
1499
	}
1500
	// FIXME: When we move to PHP 7 we can use "intdiv($sec % X, Y)" etc
1501 fedbe5af stilez
	list($d, $h, $m, $s) = array(	(int)($showhoursonly ? 0 : $sec/86400),
1502 005097dd stilez
					(int)(($showhoursonly ? $sec : $sec % 86400)/3600),
1503 8c91c89f stilez
					(int)(($sec % 3600)/60),
1504
					$sec % 60
1505
				);
1506
	return ($d > 0 ? $d . 'd ' : '') . sprintf('%02d:%02d:%02d', $h, $m, $s);
1507 9ebe7028 gnhb
}
1508 8eb2f33a Scott Ullrich
1509 63292199 gnhb
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1510
1511 23a193da Phil Davis
function get_ppp_uptime($port) {
1512
	if (file_exists("/conf/{$port}.log")) {
1513 5fa78adc Renato Botelho
		$saved_time = file_get_contents("/conf/{$port}.log");
1514 4de8f7ba Phil Davis
		$uptime_data = explode("\n", $saved_time);
1515
		$sec = 0;
1516 23a193da Phil Davis
		foreach ($uptime_data as $upt) {
1517 63292199 gnhb
			$sec += substr($upt, 1 + strpos($upt, " "));
1518 5fa78adc Renato Botelho
		}
1519 8c91c89f stilez
		return convert_seconds_to_dhms($sec);
1520 63292199 gnhb
	} else {
1521 7d1b238c Carlos Eduardo Ramos
		$total_time = gettext("No history data found!");
1522 63292199 gnhb
		return $total_time;
1523
	}
1524
}
1525 8eb2f33a Scott Ullrich
1526 6189988d Scott Dale
//returns interface information
1527
function get_interface_info($ifdescr) {
1528 cffe41cb Ermal
	global $config, $g;
1529 6189988d Scott Dale
1530
	$ifinfo = array();
1531 23a193da Phil Davis
	if (empty($config['interfaces'][$ifdescr])) {
1532 67ee1ec5 Ermal Luçi
		return;
1533 23a193da Phil Davis
	}
1534 ebdbdbc2 gnhb
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1535 cffe41cb Ermal
	$ifinfo['if'] = get_real_interface($ifdescr);
1536 6189988d Scott Dale
1537 cb074893 Ermal Lu?i
	$chkif = $ifinfo['if'];
1538
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1539
	$ifinfo['status'] = $ifinfotmp['status'];
1540 23a193da Phil Davis
	if (empty($ifinfo['status'])) {
1541 5fa78adc Renato Botelho
		$ifinfo['status'] = "down";
1542 23a193da Phil Davis
	}
1543 cb074893 Ermal Lu?i
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1544 2d2e466c Ermal LUÇI
	$ifinfo['mtu'] = $ifinfotmp['mtu'];
1545 cb074893 Ermal Lu?i
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1546
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1547 58418355 smos
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1548 15cc0894 Seth Mos
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1549
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1550 23a193da Phil Davis
	if (isset($ifinfotmp['link0'])) {
1551 cb074893 Ermal Lu?i
		$link0 = "down";
1552 23a193da Phil Davis
	}
1553 cffe41cb Ermal
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1554 5fa78adc Renato Botelho
	// $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1555
	// $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1556
	$ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1557
	$ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1558
	$ifinfo['collisions'] = $ifinfotmp['collisions'];
1559 6189988d Scott Dale
1560 01385b0c Scott Ullrich
	/* Use pfctl for non wrapping 64 bit counters */
1561 b5a8483c Seth Mos
	/* Pass */
1562 cb074893 Ermal Lu?i
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1563 971eaab5 Seth Mos
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1564
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1565 15cc0894 Seth Mos
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1566
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1567 971eaab5 Seth Mos
	$in4_pass = $pf_in4_pass[5];
1568
	$out4_pass = $pf_out4_pass[5];
1569
	$in4_pass_packets = $pf_in4_pass[3];
1570
	$out4_pass_packets = $pf_out4_pass[3];
1571 15cc0894 Seth Mos
	$in6_pass = $pf_in6_pass[5];
1572
	$out6_pass = $pf_out6_pass[5];
1573
	$in6_pass_packets = $pf_in6_pass[3];
1574
	$out6_pass_packets = $pf_out6_pass[3];
1575
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1576
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1577
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1578 4bdfa5dd Phil Davis
	$ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets;
1579 01385b0c Scott Ullrich
1580 971eaab5 Seth Mos
	/* Block */
1581
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1582
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1583 15cc0894 Seth Mos
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1584
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1585 971eaab5 Seth Mos
	$in4_block = $pf_in4_block[5];
1586
	$out4_block = $pf_out4_block[5];
1587
	$in4_block_packets = $pf_in4_block[3];
1588
	$out4_block_packets = $pf_out4_block[3];
1589 15cc0894 Seth Mos
	$in6_block = $pf_in6_block[5];
1590
	$out6_block = $pf_out6_block[5];
1591
	$in6_block_packets = $pf_in6_block[3];
1592
	$out6_block_packets = $pf_out6_block[3];
1593
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1594
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1595
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1596
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1597
1598
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1599
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1600
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1601 4bdfa5dd Phil Davis
	$ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets;
1602 5fa78adc Renato Botelho
1603 63161b3f Ermal Luçi
	$ifconfiginfo = "";
1604 59db783a gnhb
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1605
	switch ($link_type) {
1606 23a193da Phil Davis
		/* DHCP? -> see if dhclient is up */
1607
		case "dhcp":
1608
			/* see if dhclient is up */
1609
			if (find_dhclient_process($ifinfo['if']) != 0) {
1610
				$ifinfo['dhcplink'] = "up";
1611
			} else {
1612
				$ifinfo['dhcplink'] = "down";
1613 badbe349 gnhb
			}
1614 23a193da Phil Davis
1615 611ae852 Ermal
			break;
1616 23a193da Phil Davis
		/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1617
		case "pppoe":
1618
		case "pptp":
1619
		case "l2tp":
1620
			if ($ifinfo['status'] == "up" && !isset($link0)) {
1621
				/* get PPPoE link status for dial on demand */
1622
				$ifinfo["{$link_type}link"] = "up";
1623
			} else {
1624
				$ifinfo["{$link_type}link"] = "down";
1625 4adf752c smos
			}
1626 23a193da Phil Davis
1627
			break;
1628
		/* PPP interface? -> get uptime for this session and cumulative uptime from the persistent log file in conf */
1629
		case "ppp":
1630
			if ($ifinfo['status'] == "up") {
1631
				$ifinfo['ppplink'] = "up";
1632
			} else {
1633
				$ifinfo['ppplink'] = "down" ;
1634 4adf752c smos
			}
1635 23a193da Phil Davis
1636
			if (empty($ifinfo['status'])) {
1637
				$ifinfo['status'] = "down";
1638
			}
1639
1640
			if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1641
				foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1642
					if ($config['interfaces'][$ifdescr]['if'] == $ppp['if']) {
1643
						break;
1644
					}
1645
				}
1646
			}
1647
			$dev = $ppp['ports'];
1648
			if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev)) {
1649
				break;
1650
			}
1651
			if (!file_exists($dev)) {
1652
				$ifinfo['nodevice'] = 1;
1653
				$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");
1654
			}
1655
1656
			$usbmodemoutput = array();
1657 84c82d3d doktornotor
			exec("/usr/sbin/usbconfig", $usbmodemoutput);
1658 23a193da Phil Davis
			$mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}";
1659
			if (file_exists($mondev)) {
1660
				$cellstats = file($mondev);
1661
				/* skip header */
1662
				$a_cellstats = explode(",", $cellstats[1]);
1663
				if (preg_match("/huawei/i", implode("\n", $usbmodemoutput))) {
1664
					$ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]);
1665
					$ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1666
					$ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]);
1667
					$ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11]));
1668
				}
1669
				if (preg_match("/zte/i", implode("\n", $usbmodemoutput))) {
1670
					$ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]);
1671
					$ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1672
					$ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]);
1673
					$ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11]));
1674
				}
1675
				$ifinfo['cell_upstream'] = $a_cellstats[4];
1676
				$ifinfo['cell_downstream'] = trim($a_cellstats[5]);
1677
				$ifinfo['cell_sent'] = $a_cellstats[6];
1678
				$ifinfo['cell_received'] = trim($a_cellstats[7]);
1679
				$ifinfo['cell_bwupstream'] = $a_cellstats[8];
1680
				$ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]);
1681
			}
1682
			// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1683
			if (isset($ppp['uptime'])) {
1684
				$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1685
			}
1686
			break;
1687
		default:
1688
			break;
1689 6189988d Scott Dale
	}
1690 5fa78adc Renato Botelho
1691 59db783a gnhb
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1692
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1693 8c91c89f stilez
		$ifinfo['ppp_uptime'] = convert_seconds_to_dhms($sec);
1694 59db783a gnhb
	}
1695 5fa78adc Renato Botelho
1696 6189988d Scott Dale
	if ($ifinfo['status'] == "up") {
1697
		/* try to determine media with ifconfig */
1698
		unset($ifconfiginfo);
1699 818a6b7d Seth Mos
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1700
		$wifconfiginfo = array();
1701 23a193da Phil Davis
		if (is_interface_wireless($ifdescr)) {
1702 818a6b7d Seth Mos
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1703
			array_shift($wifconfiginfo);
1704
		}
1705 6189988d Scott Dale
		$matches = "";
1706
		foreach ($ifconfiginfo as $ici) {
1707
1708
			/* don't list media/speed for wireless cards, as it always
1709
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1710
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1711
				$ifinfo['media'] = $matches[1];
1712
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1713
				$ifinfo['media'] = $matches[1];
1714
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1715
				$ifinfo['media'] = $matches[1];
1716
			}
1717
1718
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1719 23a193da Phil Davis
				if ($matches[1] != "active") {
1720 6189988d Scott Dale
					$ifinfo['status'] = $matches[1];
1721 23a193da Phil Davis
				}
1722
				if ($ifinfo['status'] == gettext("running")) {
1723 7d1b238c Carlos Eduardo Ramos
					$ifinfo['status'] = gettext("up");
1724 23a193da Phil Davis
				}
1725 6189988d Scott Dale
			}
1726
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1727
				$ifinfo['channel'] = $matches[1];
1728
			}
1729
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1730 23a193da Phil Davis
				if ($matches[1][0] == '"') {
1731 6189988d Scott Dale
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1732 23a193da Phil Davis
				}
1733
				else {
1734 6189988d Scott Dale
					$ifinfo['ssid'] = $matches[1];
1735 23a193da Phil Davis
				}
1736 6189988d Scott Dale
			}
1737 0b29093b jim-p
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1738
				$ifinfo['laggproto'] = $matches[1];
1739
			}
1740
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1741
				$ifinfo['laggport'][] = $matches[1];
1742
			}
1743 6189988d Scott Dale
		}
1744 23a193da Phil Davis
		foreach ($wifconfiginfo as $ici) {
1745 818a6b7d Seth Mos
			$elements = preg_split("/[ ]+/i", $ici);
1746
			if ($elements[0] != "") {
1747
				$ifinfo['bssid'] = $elements[0];
1748
			}
1749
			if ($elements[3] != "") {
1750
				$ifinfo['rate'] = $elements[3];
1751
			}
1752
			if ($elements[4] != "") {
1753
				$ifinfo['rssi'] = $elements[4];
1754
			}
1755
		}
1756 67ee1ec5 Ermal Luçi
		/* lookup the gateway */
1757 2bbb79cb Seth Mos
		if (interface_has_gateway($ifdescr)) {
1758 ebdbdbc2 gnhb
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1759 2bbb79cb Seth Mos
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1760
		}
1761 6189988d Scott Dale
	}
1762
1763
	$bridge = "";
1764 7ec05d27 Ermal Luçi
	$bridge = link_interface_to_bridge($ifdescr);
1765 23a193da Phil Davis
	if ($bridge) {
1766 6189988d Scott Dale
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1767 23a193da Phil Davis
		if (stristr($bridge_text, "blocking") <> false) {
1768 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1769 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1770 23a193da Phil Davis
		} else if (stristr($bridge_text, "learning") <> false) {
1771 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("learning");
1772 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1773 23a193da Phil Davis
		} else if (stristr($bridge_text, "forwarding") <> false) {
1774 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("forwarding");
1775 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1776
		}
1777
	}
1778
1779
	return $ifinfo;
1780
}
1781
1782
//returns cpu speed of processor. Good for determining capabilities of machine
1783
function get_cpu_speed() {
1784 971de1f9 Renato Botelho
	return get_single_sysctl("hw.clockrate");
1785 6189988d Scott Dale
}
1786 fab7ff44 Bill Marquette
1787 df0cb10b Phil Davis
function get_uptime_sec() {
1788
	$boottime = "";
1789
	$matches = "";
1790 971de1f9 Renato Botelho
	$boottime = get_single_sysctl("kern.boottime");
1791
	preg_match("/sec = (\d+)/", $boottime, $matches);
1792 df0cb10b Phil Davis
	$boottime = $matches[1];
1793 23a193da Phil Davis
	if (intval($boottime) == 0) {
1794 df0cb10b Phil Davis
		return 0;
1795 23a193da Phil Davis
	}
1796 df0cb10b Phil Davis
1797
	$uptime = time() - $boottime;
1798
	return $uptime;
1799
}
1800
1801 a5f94f14 Scott Ullrich
function add_hostname_to_watch($hostname) {
1802 23a193da Phil Davis
	if (!is_dir("/var/db/dnscache")) {
1803 c941ea1c Seth Mos
		mkdir("/var/db/dnscache");
1804
	}
1805 2d0c5e3e Renato Botelho
	$result = array();
1806 23a193da Phil Davis
	if ((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1807 581e772e Seth Mos
		$domrecords = array();
1808
		$domips = array();
1809 84c82d3d doktornotor
		exec("/usr/bin/host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1810 23a193da Phil Davis
		if ($rethost == 0) {
1811
			foreach ($domrecords as $domr) {
1812 581e772e Seth Mos
				$doml = explode(" ", $domr);
1813
				$domip = $doml[3];
1814
				/* fill array with domain ip addresses */
1815 23a193da Phil Davis
				if (is_ipaddr($domip)) {
1816 581e772e Seth Mos
					$domips[] = $domip;
1817
				}
1818
			}
1819
		}
1820
		sort($domips);
1821
		$contents = "";
1822 23a193da Phil Davis
		if (!empty($domips)) {
1823
			foreach ($domips as $ip) {
1824 162c059e Seth Mos
				$contents .= "$ip\n";
1825
			}
1826 581e772e Seth Mos
		}
1827
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1828 aa57f965 Renato Botelho
		/* Remove empty elements */
1829
		$result = array_filter(explode("\n", $contents), 'strlen');
1830 a5f94f14 Scott Ullrich
	}
1831 2d0c5e3e Renato Botelho
	return $result;
1832 a5f94f14 Scott Ullrich
}
1833
1834 5ed54b93 Seth Mos
function is_fqdn($fqdn) {
1835
	$hostname = false;
1836 23a193da Phil Davis
	if (preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1837 5ed54b93 Seth Mos
		$hostname = true;
1838
	}
1839 23a193da Phil Davis
	if (preg_match("/\.\./", $fqdn)) {
1840 5ed54b93 Seth Mos
		$hostname = false;
1841
	}
1842 23a193da Phil Davis
	if (preg_match("/^\./i", $fqdn)) {
1843 5ed54b93 Seth Mos
		$hostname = false;
1844
	}
1845 23a193da Phil Davis
	if (preg_match("/\//i", $fqdn)) {
1846 c941ea1c Seth Mos
		$hostname = false;
1847
	}
1848 5ed54b93 Seth Mos
	return($hostname);
1849
}
1850
1851 639aaa95 Bill Marquette
function pfsense_default_state_size() {
1852 5fa78adc Renato Botelho
	/* get system memory amount */
1853
	$memory = get_memory();
1854 386758bb Phil Davis
	$physmem = $memory[0];
1855 5fa78adc Renato Botelho
	/* Be cautious and only allocate 10% of system memory to the state table */
1856 386758bb Phil Davis
	$max_states = (int) ($physmem/10)*1000;
1857 5fa78adc Renato Botelho
	return $max_states;
1858 639aaa95 Bill Marquette
}
1859
1860 84aea606 jim-p
function pfsense_default_tables_size() {
1861
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1862
	return $current;
1863
}
1864
1865 fb586a16 jim-p
function pfsense_default_table_entries_size() {
1866
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1867 742844a5 NOYB
	return (trim($current));
1868 fb586a16 jim-p
}
1869
1870 7723c7e0 Seth Mos
/* Compare the current hostname DNS to the DNS cache we made
1871
 * if it has changed we return the old records
1872 046b8ba6 Renato Botelho
 * if no change we return false */
1873 7723c7e0 Seth Mos
function compare_hostname_to_dnscache($hostname) {
1874 23a193da Phil Davis
	if (!is_dir("/var/db/dnscache")) {
1875 7723c7e0 Seth Mos
		mkdir("/var/db/dnscache");
1876
	}
1877
	$hostname = trim($hostname);
1878 23a193da Phil Davis
	if (is_readable("/var/db/dnscache/{$hostname}")) {
1879 7723c7e0 Seth Mos
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1880
	} else {
1881
		$oldcontents = "";
1882
	}
1883 23a193da Phil Davis
	if ((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1884 7723c7e0 Seth Mos
		$domrecords = array();
1885
		$domips = array();
1886 84c82d3d doktornotor
		exec("/usr/bin/host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1887 23a193da Phil Davis
		if ($rethost == 0) {
1888
			foreach ($domrecords as $domr) {
1889 7723c7e0 Seth Mos
				$doml = explode(" ", $domr);
1890
				$domip = $doml[3];
1891
				/* fill array with domain ip addresses */
1892 23a193da Phil Davis
				if (is_ipaddr($domip)) {
1893 7723c7e0 Seth Mos
					$domips[] = $domip;
1894
				}
1895
			}
1896
		}
1897
		sort($domips);
1898
		$contents = "";
1899 23a193da Phil Davis
		if (!empty($domips)) {
1900
			foreach ($domips as $ip) {
1901 7723c7e0 Seth Mos
				$contents .= "$ip\n";
1902
			}
1903
		}
1904
	}
1905
1906 23a193da Phil Davis
	if (trim($oldcontents) != trim($contents)) {
1907
		if ($g['debug']) {
1908 addc0439 Renato Botelho
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1909 a5f91ef4 Seth Mos
		}
1910 7723c7e0 Seth Mos
		return ($oldcontents);
1911
	} else {
1912
		return false;
1913
	}
1914
}
1915
1916 09f18f59 jim-p
/*
1917 7530177c jim-p
 * load_crypto() - Load crypto modules if enabled in config.
1918 09f18f59 jim-p
 */
1919 7530177c jim-p
function load_crypto() {
1920 09f18f59 jim-p
	global $config, $g;
1921 7530177c jim-p
	$crypto_modules = array('glxsb', 'aesni');
1922
1923 23a193da Phil Davis
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules)) {
1924 7530177c jim-p
		return false;
1925 23a193da Phil Davis
	}
1926 7530177c jim-p
1927 3d74b803 jim-p
	if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) {
1928 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Loading %s cryptographic accelerator module."), $config['system']['crypto_hardware']));
1929 7530177c jim-p
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1930 09f18f59 jim-p
	}
1931
}
1932
1933 f60156f6 jim-p
/*
1934
 * load_thermal_hardware() - Load temperature monitor kernel module
1935
 */
1936
function load_thermal_hardware() {
1937
	global $config, $g;
1938
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1939
1940 23a193da Phil Davis
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules)) {
1941 f60156f6 jim-p
		return false;
1942 23a193da Phil Davis
	}
1943 f60156f6 jim-p
1944 3d74b803 jim-p
	if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) {
1945 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Loading %s thermal monitor module."), $config['system']['thermal_hardware']));
1946 f60156f6 jim-p
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1947
	}
1948
}
1949
1950 cde4f5d3 Scott Ullrich
/****f* pfsense-utils/isvm
1951
 * NAME
1952
 *   isvm
1953
 * INPUTS
1954 c96e71d1 Renato Botelho
 *	none
1955 cde4f5d3 Scott Ullrich
 * RESULT
1956
 *   returns true if machine is running under a virtual environment
1957
 ******/
1958
function isvm() {
1959 7e36f71c Renato Botelho
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86", "VirtualBox");
1960 f6bea44d Renato Botelho
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $output, $rc);
1961 7e36f71c Renato Botelho
1962 23a193da Phil Davis
	if ($rc != 0 || !isset($output[0])) {
1963 7e36f71c Renato Botelho
		return false;
1964 23a193da Phil Davis
	}
1965 7e36f71c Renato Botelho
1966 23a193da Phil Davis
	foreach ($virtualenvs as $virtualenv) {
1967
		if (stripos($output[0], $virtualenv) !== false) {
1968 58897b8c Warren Baker
			return true;
1969 23a193da Phil Davis
		}
1970
	}
1971 58897b8c Warren Baker
1972
	return false;
1973 cde4f5d3 Scott Ullrich
}
1974
1975 e0d0eb71 Scott Ullrich
function get_freebsd_version() {
1976 54597012 Renato Botelho
	$version = explode(".", php_uname("r"));
1977
	return $version[0];
1978 e0d0eb71 Scott Ullrich
}
1979
1980 a320af18 Chris Buechler
function download_file($url, $destination, $verify_ssl = true, $connect_timeout = 5, $timeout = 0) {
1981 ffd7802a Renato Botelho
	global $config, $g;
1982
1983
	$fp = fopen($destination, "wb");
1984
1985 23a193da Phil Davis
	if (!$fp) {
1986 ffd7802a Renato Botelho
		return false;
1987 23a193da Phil Davis
	}
1988 ffd7802a Renato Botelho
1989
	$ch = curl_init();
1990
	curl_setopt($ch, CURLOPT_URL, $url);
1991
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
1992
	curl_setopt($ch, CURLOPT_FILE, $fp);
1993
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1994
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1995
	curl_setopt($ch, CURLOPT_HEADER, false);
1996
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1997 48600bc6 Renato Botelho
	if (!isset($config['system']['do_not_send_uniqueid'])) {
1998 0d3d86c8 Renato Botelho
		curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . $g['product_version'] . ':' . system_get_uniqueid());
1999 6c07db48 Phil Davis
	} else {
2000 5779ade6 Renato Botelho
		curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . $g['product_version']);
2001 6c07db48 Phil Davis
	}
2002 ffd7802a Renato Botelho
2003
	if (!empty($config['system']['proxyurl'])) {
2004
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
2005 23a193da Phil Davis
		if (!empty($config['system']['proxyport'])) {
2006 ffd7802a Renato Botelho
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
2007 23a193da Phil Davis
		}
2008 ffd7802a Renato Botelho
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2009
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
2010
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
2011
		}
2012
	}
2013
2014
	@curl_exec($ch);
2015
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2016
	fclose($fp);
2017
	curl_close($ch);
2018 fd4dbabc Chris Buechler
	if ($http_code == 200) {
2019
		return true;
2020
	} else {
2021 e8c516a0 Phil Davis
		log_error(sprintf(gettext('Download file failed with status code %1$s. URL: %2$s'), $http_code, $url));
2022 fd4dbabc Chris Buechler
		unlink_if_exists($destination);
2023
		return false;
2024
	}
2025 ffd7802a Renato Botelho
}
2026
2027 eb38f9a8 Chris Buechler
function download_file_with_progress_bar($url, $destination, $verify_ssl = true, $readbody = 'read_body', $connect_timeout = 5, $timeout = 0) {
2028 bfc15aca Ermal LUÇI
	global $config, $g;
2029
	global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
2030 4de8f7ba Phil Davis
	$file_size = 1;
2031 5fa78adc Renato Botelho
	$downloaded = 1;
2032 e961bd67 phildd
	$first_progress_update = TRUE;
2033 5fa78adc Renato Botelho
	/* open destination file */
2034 eb38f9a8 Chris Buechler
	$fout = fopen($destination, "wb");
2035 5fa78adc Renato Botelho
2036 eb38f9a8 Chris Buechler
	if (!$fout) {
2037
		return false;
2038
	}
2039 5fa78adc Renato Botelho
	/*
2040
	 *      Originally by Author: Keyvan Minoukadeh
2041
	 *      Modified by Scott Ullrich to return Content-Length size
2042
	 */
2043
	$ch = curl_init();
2044 eb38f9a8 Chris Buechler
	curl_setopt($ch, CURLOPT_URL, $url);
2045
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
2046 5fa78adc Renato Botelho
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
2047
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
2048
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
2049
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
2050
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
2051
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
2052 48600bc6 Renato Botelho
	if (!isset($config['system']['do_not_send_uniqueid'])) {
2053 0d3d86c8 Renato Botelho
		curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . $g['product_version'] . ':' . system_get_uniqueid());
2054 6c07db48 Phil Davis
	} else {
2055 5779ade6 Renato Botelho
		curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . $g['product_version']);
2056 6c07db48 Phil Davis
	}
2057 b31da21e Scott Ullrich
2058 42c07003 Ermal
	if (!empty($config['system']['proxyurl'])) {
2059
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
2060 23a193da Phil Davis
		if (!empty($config['system']['proxyport'])) {
2061 42c07003 Ermal
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
2062 23a193da Phil Davis
		}
2063 42c07003 Ermal
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2064
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
2065 2a57a4d1 Ermal
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
2066 42c07003 Ermal
		}
2067
	}
2068
2069 5fa78adc Renato Botelho
	@curl_exec($ch);
2070
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2071 eb38f9a8 Chris Buechler
	fclose($fout);
2072 5fa78adc Renato Botelho
	curl_close($ch);
2073 eb38f9a8 Chris Buechler
	if ($http_code == 200) {
2074
		return true;
2075
	} else {
2076 e8c516a0 Phil Davis
		log_error(sprintf(gettext('Download file failed with status code %1$s. URL: %2$s'), $http_code, $url));
2077 eb38f9a8 Chris Buechler
		unlink_if_exists($destination);
2078
		return false;
2079
	}
2080 b31da21e Scott Ullrich
}
2081
2082
function read_header($ch, $string) {
2083 5fa78adc Renato Botelho
	global $file_size, $fout;
2084
	$length = strlen($string);
2085
	$regs = "";
2086
	preg_match("/(Content-Length:) (.*)/", $string, $regs);
2087 23a193da Phil Davis
	if ($regs[2] <> "") {
2088 5fa78adc Renato Botelho
		$file_size = intval($regs[2]);
2089
	}
2090
	ob_flush();
2091
	return $length;
2092 b31da21e Scott Ullrich
}
2093
2094
function read_body($ch, $string) {
2095 5fa78adc Renato Botelho
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $first_progress_update;
2096
	global $pkg_interface;
2097
	$length = strlen($string);
2098
	$downloaded += intval($length);
2099 23a193da Phil Davis
	if ($file_size > 0) {
2100 5fa78adc Renato Botelho
		$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
2101
		$downloadProgress = 100 - $downloadProgress;
2102 23a193da Phil Davis
	} else {
2103 5fa78adc Renato Botelho
		$downloadProgress = 0;
2104 23a193da Phil Davis
	}
2105
	if ($lastseen <> $downloadProgress and $downloadProgress < 101) {
2106
		if ($sendto == "status") {
2107
			if ($pkg_interface == "console") {
2108
				if (($downloadProgress % 10) == 0 || $downloadProgress < 10) {
2109 03b2cab6 Ermal
					$tostatus = $static_status . $downloadProgress . "%";
2110 2a315bee Phil Davis
					if ($downloadProgress == 100) {
2111 a3da8f50 Ermal
						$tostatus = $tostatus . "\r";
2112 2a315bee Phil Davis
					}
2113 03b2cab6 Ermal
					update_status($tostatus);
2114
				}
2115
			} else {
2116
				$tostatus = $static_status . $downloadProgress . "%";
2117 5fa78adc Renato Botelho
				update_status($tostatus);
2118 03b2cab6 Ermal
			}
2119 5fa78adc Renato Botelho
		} else {
2120 23a193da Phil Davis
			if ($pkg_interface == "console") {
2121
				if (($downloadProgress % 10) == 0 || $downloadProgress < 10) {
2122 03b2cab6 Ermal
					$tooutput = $static_output . $downloadProgress . "%";
2123 2a315bee Phil Davis
					if ($downloadProgress == 100) {
2124 a3da8f50 Ermal
						$tooutput = $tooutput . "\r";
2125 2a315bee Phil Davis
					}
2126 03b2cab6 Ermal
					update_output_window($tooutput);
2127
				}
2128
			} else {
2129
				$tooutput = $static_output . $downloadProgress . "%";
2130
				update_output_window($tooutput);
2131
			}
2132 5fa78adc Renato Botelho
		}
2133 23a193da Phil Davis
		if (($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) {
2134
			update_progress_bar($downloadProgress, $first_progress_update);
2135
			$first_progress_update = FALSE;
2136
		}
2137 5fa78adc Renato Botelho
		$lastseen = $downloadProgress;
2138
	}
2139 23a193da Phil Davis
	if ($fout) {
2140 5fa78adc Renato Botelho
		fwrite($fout, $string);
2141 23a193da Phil Davis
	}
2142 5fa78adc Renato Botelho
	ob_flush();
2143
	return $length;
2144 b31da21e Scott Ullrich
}
2145
2146 84677257 Scott Ullrich
/*
2147
 *   update_output_window: update bottom textarea dynamically.
2148
 */
2149
function update_output_window($text) {
2150 5fa78adc Renato Botelho
	global $pkg_interface;
2151
	$log = preg_replace("/\n/", "\\n", $text);
2152 23a193da Phil Davis
	if ($pkg_interface != "console") {
2153 2d26ee5e Sjon Hortensius
?>
2154 8fd9052f Colin Fleming
<script type="text/javascript">
2155
//<![CDATA[
2156 2d26ee5e Sjon Hortensius
	document.getElementById("output").textContent="<?=htmlspecialchars($log)?>";
2157
	document.getElementById("output").scrollTop = document.getElementById("output").scrollHeight;
2158 8fd9052f Colin Fleming
//]]>
2159 2d26ee5e Sjon Hortensius
</script>
2160
<?php
2161 5fa78adc Renato Botelho
	}
2162
	/* ensure that contents are written out */
2163
	ob_flush();
2164 84677257 Scott Ullrich
}
2165
2166
/*
2167 82acb8b3 Phil Davis
 *   update_status: update top textarea dynamically.
2168 84677257 Scott Ullrich
 */
2169
function update_status($status) {
2170 5fa78adc Renato Botelho
	global $pkg_interface;
2171 1da49511 Renato Botelho
2172 23a193da Phil Davis
	if ($pkg_interface == "console") {
2173 489c102b BBcan177
		print ("{$status}");
2174 5fa78adc Renato Botelho
	}
2175 2d26ee5e Sjon Hortensius
2176 5fa78adc Renato Botelho
	/* ensure that contents are written out */
2177
	ob_flush();
2178 84677257 Scott Ullrich
}
2179
2180
/*
2181 e961bd67 phildd
 * update_progress_bar($percent, $first_time): updates the javascript driven progress bar.
2182 84677257 Scott Ullrich
 */
2183 e961bd67 phildd
function update_progress_bar($percent, $first_time) {
2184 5fa78adc Renato Botelho
	global $pkg_interface;
2185 23a193da Phil Davis
	if ($percent > 100) {
2186
		$percent = 1;
2187
	}
2188
	if ($pkg_interface <> "console") {
2189 8fd9052f Colin Fleming
		echo '<script type="text/javascript">';
2190
		echo "\n//<![CDATA[\n";
2191 66066eda Stephen Beaver
		echo 'document.getElementById("progressbar").style.width="'. $percent.'%"';
2192 8fd9052f Colin Fleming
		echo "\n//]]>\n";
2193
		echo '</script>';
2194 5fa78adc Renato Botelho
	} else {
2195 23a193da Phil Davis
		if (!($first_time)) {
2196 e961bd67 phildd
			echo "\x08\x08\x08\x08\x08";
2197 23a193da Phil Davis
		}
2198 e961bd67 phildd
		echo sprintf("%4d%%", $percent);
2199 5fa78adc Renato Botelho
	}
2200 84677257 Scott Ullrich
}
2201
2202 f5d637bc Scott Ullrich
/* Split() is being DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged. */
2203 23a193da Phil Davis
if (!function_exists("split")) {
2204 5aa68a55 Renato Botelho
	function split($separator, $haystack, $limit = null) {
2205
		log_error("deprecated split() call with separator '{$separator}'");
2206
		return preg_split($separator, $haystack, $limit);
2207 f5d637bc Scott Ullrich
	}
2208
}
2209
2210 9dfd9007 Phil Davis
function update_alias_name($new_alias_name, $orig_alias_name) {
2211
	if (!$orig_alias_name) {
2212
		return;
2213
	}
2214
2215
	// Firewall rules
2216
	update_alias_names_upon_change(array('filter', 'rule'), array('source', 'address'), $new_alias_name, $orig_alias_name);
2217
	update_alias_names_upon_change(array('filter', 'rule'), array('destination', 'address'), $new_alias_name, $orig_alias_name);
2218
	update_alias_names_upon_change(array('filter', 'rule'), array('source', 'port'), $new_alias_name, $orig_alias_name);
2219
	update_alias_names_upon_change(array('filter', 'rule'), array('destination', 'port'), $new_alias_name, $orig_alias_name);
2220
	// NAT Rules
2221
	update_alias_names_upon_change(array('nat', 'rule'), array('source', 'address'), $new_alias_name, $orig_alias_name);
2222
	update_alias_names_upon_change(array('nat', 'rule'), array('source', 'port'), $new_alias_name, $orig_alias_name);
2223
	update_alias_names_upon_change(array('nat', 'rule'), array('destination', 'address'), $new_alias_name, $orig_alias_name);
2224
	update_alias_names_upon_change(array('nat', 'rule'), array('destination', 'port'), $new_alias_name, $orig_alias_name);
2225
	update_alias_names_upon_change(array('nat', 'rule'), array('target'), $new_alias_name, $orig_alias_name);
2226
	update_alias_names_upon_change(array('nat', 'rule'), array('local-port'), $new_alias_name, $orig_alias_name);
2227
	// NAT 1:1 Rules
2228
	//update_alias_names_upon_change(array('nat', 'onetoone'), array('external'), $new_alias_name, $orig_alias_name);
2229
	//update_alias_names_upon_change(array('nat', 'onetoone'), array('source', 'address'), $new_alias_name, $orig_alias_name);
2230
	update_alias_names_upon_change(array('nat', 'onetoone'), array('destination', 'address'), $new_alias_name, $orig_alias_name);
2231
	// NAT Outbound Rules
2232
	update_alias_names_upon_change(array('nat', 'outbound', 'rule'), array('source', 'network'), $new_alias_name, $orig_alias_name);
2233
	update_alias_names_upon_change(array('nat', 'outbound', 'rule'), array('sourceport'), $new_alias_name, $orig_alias_name);
2234
	update_alias_names_upon_change(array('nat', 'outbound', 'rule'), array('destination', 'address'), $new_alias_name, $orig_alias_name);
2235
	update_alias_names_upon_change(array('nat', 'outbound', 'rule'), array('dstport'), $new_alias_name, $orig_alias_name);
2236
	update_alias_names_upon_change(array('nat', 'outbound', 'rule'), array('target'), $new_alias_name, $orig_alias_name);
2237
	// Alias in an alias
2238
	update_alias_names_upon_change(array('aliases', 'alias'), array('address'), $new_alias_name, $orig_alias_name);
2239
}
2240
2241 f1ac1733 Erik Fonnesbeck
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
2242 978fd2e8 Scott Ullrich
	global $g, $config, $pconfig, $debug;
2243 23a193da Phil Davis
	if (!$origname) {
2244 b6db8ea3 sullrich
		return;
2245 23a193da Phil Davis
	}
2246 b6db8ea3 sullrich
2247 f1ac1733 Erik Fonnesbeck
	$sectionref = &$config;
2248 23a193da Phil Davis
	foreach ($section as $sectionname) {
2249
		if (is_array($sectionref) && isset($sectionref[$sectionname])) {
2250 f1ac1733 Erik Fonnesbeck
			$sectionref = &$sectionref[$sectionname];
2251 23a193da Phil Davis
		} else {
2252 f1ac1733 Erik Fonnesbeck
			return;
2253 23a193da Phil Davis
		}
2254 f1ac1733 Erik Fonnesbeck
	}
2255
2256 23a193da Phil Davis
	if ($debug) {
2257
		$fd = fopen("{$g['tmp_path']}/print_r", "a");
2258
		fwrite($fd, print_r($pconfig, true));
2259
	}
2260 b6db8ea3 sullrich
2261 23a193da Phil Davis
	if (is_array($sectionref)) {
2262
		foreach ($sectionref as $itemkey => $item) {
2263
			if ($debug) {
2264
				fwrite($fd, "$itemkey\n");
2265
			}
2266 f1ac1733 Erik Fonnesbeck
2267
			$fieldfound = true;
2268
			$fieldref = &$sectionref[$itemkey];
2269 23a193da Phil Davis
			foreach ($field as $fieldname) {
2270
				if (is_array($fieldref) && isset($fieldref[$fieldname])) {
2271 f1ac1733 Erik Fonnesbeck
					$fieldref = &$fieldref[$fieldname];
2272 23a193da Phil Davis
				} else {
2273 f1ac1733 Erik Fonnesbeck
					$fieldfound = false;
2274
					break;
2275
				}
2276 b6db8ea3 sullrich
			}
2277 23a193da Phil Davis
			if ($fieldfound && $fieldref == $origname) {
2278
				if ($debug) {
2279
					fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
2280
				}
2281 f1ac1733 Erik Fonnesbeck
				$fieldref = $new_alias_name;
2282 b6db8ea3 sullrich
			}
2283
		}
2284
	}
2285
2286 23a193da Phil Davis
	if ($debug) {
2287
		fclose($fd);
2288
	}
2289 b6db8ea3 sullrich
2290
}
2291 f6ba4bd1 Scott Ullrich
2292 f6622167 NOYB
function parse_aliases_file($filename, $type = "url", $max_items = -1, $kflc = false) {
2293 6d1907a3 Renato Botelho
	/*
2294
	 * $filename = file to process for example blocklist like DROP:  http://www.spamhaus.org/drop/drop.txt
2295
	 * $type = if set to 'url' then subnets and ips will be returned,
2296
	 *         if set to 'url_ports' port-ranges and ports will be returned
2297
	 * $max_items = sets the maximum amount of valid items to load, -1 the default defines there is no limit.
2298
	 *
2299
	 * RETURNS an array of ip subnets and ip's or ports and port-ranges, returns NULL upon a error conditions (file not found)
2300
	 */
2301
2302 c25c6714 Chris Buechler
	if (!file_exists($filename)) {
2303
		log_error(sprintf(gettext("Could not process non-existent file from alias: %s"), $filename));
2304
		return null;
2305
	}
2306
2307 6f838722 Chris Buechler
	if (filesize($filename) == 0) {
2308
		log_error(sprintf(gettext("Could not process empty file from alias: %s"), $filename));
2309
		return null;
2310
	}
2311 6d1907a3 Renato Botelho
	$fd = @fopen($filename, 'r');
2312
	if (!$fd) {
2313 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Could not process aliases from alias: %s"), $filename));
2314 6d1907a3 Renato Botelho
		return null;
2315
	}
2316
	$items = array();
2317 f6622167 NOYB
	$comments = array();
2318 6d1907a3 Renato Botelho
	/* NOTE: fgetss() is not a typo RTFM before being smart */
2319
	while (($fc = fgetss($fd)) !== FALSE) {
2320
		$tmp = trim($fc, " \t\n\r");
2321 23a193da Phil Davis
		if (empty($tmp)) {
2322 6d1907a3 Renato Botelho
			continue;
2323 23a193da Phil Davis
		}
2324 f6622167 NOYB
		if (($kflc) && (strpos($tmp, '#') === 0)) {	// Keep Full Line Comments (lines beginning with #).
2325
			$comments[] = $tmp;
2326
		} else {
2327
			$tmp_str = strstr($tmp, '#', true);
2328
			if (!empty($tmp_str)) {
2329
				$tmp = $tmp_str;
2330
			}
2331
			$tmp_str = strstr($tmp, ' ', true);
2332
			if (!empty($tmp_str)) {
2333
				$tmp = $tmp_str;
2334
			}
2335 1dbdf228 NOYB
			$valid = (($type == "url" || $type == "urltable") && (is_ipaddr($tmp) || is_subnet($tmp))) ||
2336 e4958a8f Phil Davis
				(($type == "url_ports" || $type == "urltable_ports") && is_port_or_range($tmp));
2337 f6622167 NOYB
			if ($valid) {
2338
				$items[] = $tmp;
2339
				if (count($items) == $max_items) {
2340
					break;
2341
				}
2342 23a193da Phil Davis
			}
2343 6d1907a3 Renato Botelho
		}
2344
	}
2345
	fclose($fd);
2346 f6622167 NOYB
	return array_merge($comments, $items);
2347 6d1907a3 Renato Botelho
}
2348
2349 f6ba4bd1 Scott Ullrich
function update_alias_url_data() {
2350
	global $config, $g;
2351 e5953c68 Ermal
2352 8422cdd5 Ermal
	$updated = false;
2353
2354 f6ba4bd1 Scott Ullrich
	/* item is a url type */
2355 8422cdd5 Ermal
	$lockkey = lock('aliasurl');
2356 e5953c68 Ermal
	if (is_array($config['aliases']['alias'])) {
2357
		foreach ($config['aliases']['alias'] as $x => $alias) {
2358 23a193da Phil Davis
			if (empty($alias['aliasurl'])) {
2359 e5953c68 Ermal
				continue;
2360 23a193da Phil Davis
			}
2361 e5953c68 Ermal
2362 6d1907a3 Renato Botelho
			$address = null;
2363 2ef16014 bcyrill
			foreach ($alias['aliasurl'] as $alias_url) {
2364
				/* fetch down and add in */
2365
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
2366
				unlink($temp_filename);
2367 76590ffe Renato Botelho
				$verify_ssl = isset($config['system']['checkaliasesurlcert']);
2368 873c1701 Renato Botelho
				mkdir($temp_filename);
2369 37af5cf5 Chris Buechler
				if (!download_file($alias_url, $temp_filename . "/aliases", $verify_ssl)) {
2370
					log_error(sprintf(gettext("Failed to download alias %s"), $alias_url));
2371
					continue;
2372
				}
2373 76590ffe Renato Botelho
2374 2ef16014 bcyrill
				/* if the item is tar gzipped then extract */
2375 e45bae34 Ermal
				if (stripos($alias_url, '.tgz')) {
2376 23a193da Phil Davis
					if (!process_alias_tgz($temp_filename)) {
2377 e45bae34 Ermal
						continue;
2378 23a193da Phil Davis
					}
2379 e45bae34 Ermal
				}
2380 2ef16014 bcyrill
				if (file_exists("{$temp_filename}/aliases")) {
2381 ceb9cca7 Chris Buechler
					$address = parse_aliases_file("{$temp_filename}/aliases", $alias['type'], 5000);
2382 2ef16014 bcyrill
					mwexec("/bin/rm -rf {$temp_filename}");
2383 f6ba4bd1 Scott Ullrich
				}
2384 2ef16014 bcyrill
			}
2385 6d1907a3 Renato Botelho
			if ($address != null) {
2386
				$config['aliases']['alias'][$x]['address'] = implode(" ", $address);
2387 2ef16014 bcyrill
				$updated = true;
2388 f6ba4bd1 Scott Ullrich
			}
2389
		}
2390
	}
2391 26d060bc Ermal
	unlock($lockkey);
2392 8422cdd5 Ermal
2393
	/* Report status to callers as well */
2394
	return $updated;
2395 f6ba4bd1 Scott Ullrich
}
2396
2397
function process_alias_tgz($temp_filename) {
2398 23a193da Phil Davis
	if (!file_exists('/usr/bin/tar')) {
2399 e45bae34 Ermal
		log_error(gettext("Alias archive is a .tar/tgz file which cannot be decompressed because utility is missing!"));
2400
		return false;
2401
	}
2402 873c1701 Renato Botelho
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.tgz");
2403 f6ba4bd1 Scott Ullrich
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
2404
	unlink("{$temp_filename}/aliases.tgz");
2405
	$files_to_process = return_dir_as_array("{$temp_filename}/");
2406
	/* foreach through all extracted files and build up aliases file */
2407 e45bae34 Ermal
	$fd = @fopen("{$temp_filename}/aliases", "w");
2408
	if (!$fd) {
2409 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Could not open %s/aliases for writing!"), $temp_filename));
2410 e45bae34 Ermal
		return false;
2411
	}
2412 23a193da Phil Davis
	foreach ($files_to_process as $f2p) {
2413 e45bae34 Ermal
		$tmpfd = @fopen($f2p, 'r');
2414
		if (!$tmpfd) {
2415 e8c516a0 Phil Davis
			log_error(sprintf(gettext('The following file could not be read %1$s from %2$s'), $f2p, $temp_filename));
2416 e45bae34 Ermal
			continue;
2417
		}
2418 23a193da Phil Davis
		while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE) {
2419 e45bae34 Ermal
			fwrite($fd, $tmpbuf);
2420 23a193da Phil Davis
		}
2421 e45bae34 Ermal
		fclose($tmpfd);
2422 f6ba4bd1 Scott Ullrich
		unlink($f2p);
2423
	}
2424
	fclose($fd);
2425 e45bae34 Ermal
	unset($tmpbuf);
2426
2427
	return true;
2428 f6ba4bd1 Scott Ullrich
}
2429
2430 a76c1c45 jim-p
function version_compare_dates($a, $b) {
2431
	$a_time = strtotime($a);
2432
	$b_time = strtotime($b);
2433
2434
	if ((!$a_time) || (!$b_time)) {
2435
		return FALSE;
2436
	} else {
2437 23a193da Phil Davis
		if ($a_time < $b_time) {
2438 a76c1c45 jim-p
			return -1;
2439 23a193da Phil Davis
		} elseif ($a_time == $b_time) {
2440 a76c1c45 jim-p
			return 0;
2441 23a193da Phil Davis
		} else {
2442 a76c1c45 jim-p
			return 1;
2443 23a193da Phil Davis
		}
2444 a76c1c45 jim-p
	}
2445
}
2446
function version_get_string_value($a) {
2447
	$strs = array(
2448
		0 => "ALPHA-ALPHA",
2449
		2 => "ALPHA",
2450
		3 => "BETA",
2451
		4 => "B",
2452 5eb03383 jim-p
		5 => "C",
2453
		6 => "D",
2454
		7 => "RC",
2455 f8c8d65c Stilez
		8 => "RELEASE",
2456
		9 => "*"			// Matches all release levels
2457 a76c1c45 jim-p
	);
2458
	$major = 0;
2459
	$minor = 0;
2460
	foreach ($strs as $num => $str) {
2461
		if (substr($a, 0, strlen($str)) == $str) {
2462
			$major = $num;
2463
			$n = substr($a, strlen($str));
2464 23a193da Phil Davis
			if (is_numeric($n)) {
2465 a76c1c45 jim-p
				$minor = $n;
2466 23a193da Phil Davis
			}
2467 a76c1c45 jim-p
			break;
2468
		}
2469
	}
2470
	return "{$major}.{$minor}";
2471
}
2472
function version_compare_string($a, $b) {
2473 f8c8d65c Stilez
	// Only compare string parts if both versions give a specific release
2474
	// (If either version lacks a string part, assume intended to match all release levels)
2475 23a193da Phil Davis
	if (isset($a) && isset($b)) {
2476 c96e71d1 Renato Botelho
		return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
2477 23a193da Phil Davis
	} else {
2478 c96e71d1 Renato Botelho
		return 0;
2479 23a193da Phil Davis
	}
2480 a76c1c45 jim-p
}
2481
function version_compare_numeric($a, $b) {
2482 48081e6c Phil Davis
	$a_arr = explode('.', rtrim($a, '.'));
2483
	$b_arr = explode('.', rtrim($b, '.'));
2484 a76c1c45 jim-p
2485
	foreach ($a_arr as $n => $val) {
2486
		if (array_key_exists($n, $b_arr)) {
2487
			// So far so good, both have values at this minor version level. Compare.
2488 23a193da Phil Davis
			if ($val > $b_arr[$n]) {
2489 a76c1c45 jim-p
				return 1;
2490 23a193da Phil Davis
			} elseif ($val < $b_arr[$n]) {
2491 a76c1c45 jim-p
				return -1;
2492 23a193da Phil Davis
			}
2493 a76c1c45 jim-p
		} else {
2494
			// a is greater, since b doesn't have any minor version here.
2495
			return 1;
2496
		}
2497
	}
2498
	if (count($b_arr) > count($a_arr)) {
2499
		// b is longer than a, so it must be greater.
2500
		return -1;
2501
	} else {
2502
		// Both a and b are of equal length and value.
2503
		return 0;
2504
	}
2505
}
2506
function pfs_version_compare($cur_time, $cur_text, $remote) {
2507
	// First try date compare
2508 bda131b2 jim-p
	$v = version_compare_dates($cur_time, $remote);
2509 a76c1c45 jim-p
	if ($v === FALSE) {
2510
		// If that fails, try to compare by string
2511
		// Before anything else, simply test if the strings are equal
2512 23a193da Phil Davis
		if (($cur_text == $remote) || ($cur_time == $remote)) {
2513 a76c1c45 jim-p
			return 0;
2514 23a193da Phil Davis
		}
2515 a76c1c45 jim-p
		list($cur_num, $cur_str) = explode('-', $cur_text);
2516
		list($rem_num, $rem_str) = explode('-', $remote);
2517
2518
		// First try to compare the numeric parts of the version string.
2519
		$v = version_compare_numeric($cur_num, $rem_num);
2520
2521
		// If the numeric parts are the same, compare the string parts.
2522 23a193da Phil Davis
		if ($v == 0) {
2523 a76c1c45 jim-p
			return version_compare_string($cur_str, $rem_str);
2524 23a193da Phil Davis
		}
2525 a76c1c45 jim-p
	}
2526
	return $v;
2527
}
2528 288d095f NOYB
function process_alias_urltable($name, $type, $url, $freq, $forceupdate=false, $validateonly=false) {
2529 bf1a013f NOYB
	global $g, $config;
2530 dd042c51 Renato Botelho
2531 c7de8be4 jim-p
	$urltable_prefix = "/var/db/aliastables/";
2532
	$urltable_filename = $urltable_prefix . $name . ".txt";
2533 e9fea9dc Chris Buechler
	$tmp_urltable_filename = $urltable_filename . ".tmp";
2534 c7de8be4 jim-p
2535
	// Make the aliases directory if it doesn't exist
2536
	if (!file_exists($urltable_prefix)) {
2537
		mkdir($urltable_prefix);
2538
	} elseif (!is_dir($urltable_prefix)) {
2539
		unlink($urltable_prefix);
2540
		mkdir($urltable_prefix);
2541
	}
2542
2543
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
2544 cc293ac0 Chris Buechler
	if (!file_exists($urltable_filename) || (filesize($urltable_filename) == "0") ||
2545 23a193da Phil Davis
	    ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90)) ||
2546
	    $forceupdate) {
2547 c7de8be4 jim-p
2548
		// Try to fetch the URL supplied
2549
		conf_mount_rw();
2550 e9fea9dc Chris Buechler
		unlink_if_exists($tmp_urltable_filename);
2551 dd042c51 Renato Botelho
		$verify_ssl = isset($config['system']['checkaliasesurlcert']);
2552 e9fea9dc Chris Buechler
		if (download_file($url, $tmp_urltable_filename, $verify_ssl)) {
2553 f6622167 NOYB
			// Convert lines that begin with '$' or ';' to comments '#' instead of deleting them.
2554
			mwexec("/usr/bin/sed -i \"\" -E 's/^[[:space:]]*($|#|;)/#/g; /^#/!s/\;.*//g;' ". escapeshellarg($tmp_urltable_filename));
2555 1dbdf228 NOYB
2556 288d095f NOYB
			$type = ($type) ? $type : alias_get_type($name);	// If empty type passed, try to get it from config.
2557 1dbdf228 NOYB
2558
			$parsed_contents = parse_aliases_file($tmp_urltable_filename, $type, "-1", true);
2559 da88bf48 NOYB
			if ($type == "urltable_ports") {
2560 1dbdf228 NOYB
				$parsed_contents = group_ports($parsed_contents, true);
2561
			}
2562
			if (is_array($parsed_contents)) {
2563
				file_put_contents($urltable_filename, implode("\n", $parsed_contents));
2564 4c5cb2f6 Chris Buechler
			} else {
2565
				touch($urltable_filename);
2566 dd042c51 Renato Botelho
			}
2567 1dbdf228 NOYB
2568 bf1a013f NOYB
			/* If this backup is still there on a full install, but we aren't going to use ram disks, remove the archive since this is a transition. */
2569
			if (($g['platform'] == $g['product_name']) && !isset($config['system']['use_mfs_tmpvar'])) {
2570
				unlink_if_exists("{$g['cf_conf_path']}/RAM_Disk_Store{$urltable_filename}.tgz");
2571
			} else {
2572
				/* Update the RAM disk store with the new/updated table file. */
2573
				mwexec("cd / && /usr/bin/tar -czf \"{$g['cf_conf_path']}/RAM_Disk_Store{$urltable_filename}.tgz\" -C / \"{$urltable_filename}\"");
2574
			}
2575 e9fea9dc Chris Buechler
			unlink_if_exists($tmp_urltable_filename);
2576 23a193da Phil Davis
		} else {
2577 b913daf8 Chris Buechler
			if (!$validateonly) {
2578
				touch($urltable_filename);
2579
			}
2580 ca46f1de Chris Buechler
			conf_mount_ro();
2581
			return false;
2582 23a193da Phil Davis
		}
2583 c7de8be4 jim-p
		conf_mount_ro();
2584 966f359e Ermal
		return true;
2585 c7de8be4 jim-p
	} else {
2586 23a193da Phil Davis
		// File exists, and it doesn't need to be updated.
2587 c7de8be4 jim-p
		return -1;
2588
	}
2589
}
2590 08fd5444 jim-p
function get_real_slice_from_glabel($label) {
2591
	$label = escapeshellarg($label);
2592
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2593
}
2594
function nanobsd_get_boot_slice() {
2595
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2596
}
2597
function nanobsd_get_boot_drive() {
2598
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/pfsense | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' ' | /usr/bin/cut -d's' -f1`);
2599
}
2600
function nanobsd_get_active_slice() {
2601
	$boot_drive = nanobsd_get_boot_drive();
2602
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2603
2604
	return "{$boot_drive}s{$active}";
2605
}
2606
function nanobsd_get_size() {
2607
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2608
}
2609 2b5f276f jim-p
function nanobsd_switch_boot_slice() {
2610 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2611
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2612
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2613
	nanobsd_detect_slice_info();
2614
2615 2b5f276f jim-p
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2616
		$slice = $TOFLASH;
2617
	} else {
2618
		$slice = $BOOTFLASH;
2619
	}
2620
2621 23a193da Phil Davis
	for ($i = 0; $i < ob_get_level(); $i++) {
2622
		ob_end_flush();
2623
	}
2624 08fd5444 jim-p
	ob_implicit_flush(1);
2625 23a193da Phil Davis
	if (strstr($slice, "s2")) {
2626 4de8f7ba Phil Davis
		$ASLICE = "2";
2627
		$AOLDSLICE = "1";
2628
		$AGLABEL_SLICE = "pfsense1";
2629
		$AUFS_ID = "1";
2630
		$AOLD_UFS_ID = "0";
2631 08fd5444 jim-p
	} else {
2632 4de8f7ba Phil Davis
		$ASLICE = "1";
2633
		$AOLDSLICE = "2";
2634
		$AGLABEL_SLICE = "pfsense0";
2635
		$AUFS_ID = "0";
2636
		$AOLD_UFS_ID = "1";
2637
	}
2638
	$ATOFLASH = "{$BOOT_DRIVE}s{$ASLICE}";
2639
	$ACOMPLETE_PATH = "{$BOOT_DRIVE}s{$ASLICE}a";
2640
	$ABOOTFLASH = "{$BOOT_DRIVE}s{$AOLDSLICE}";
2641 08fd5444 jim-p
	conf_mount_rw();
2642 971de1f9 Renato Botelho
	set_single_sysctl("kern.geom.debugflags", "16");
2643 84c82d3d doktornotor
	exec("/sbin/gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2644 08fd5444 jim-p
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2645 2b5f276f jim-p
	// We can't update these if they are mounted now.
2646
	if ($BOOTFLASH != $slice) {
2647
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2648
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2649
	}
2650 971de1f9 Renato Botelho
	set_single_sysctl("kern.geom.debugflags", "0");
2651 08fd5444 jim-p
	conf_mount_ro();
2652
}
2653 2b5f276f jim-p
function nanobsd_clone_slice() {
2654 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2655
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2656
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2657
	nanobsd_detect_slice_info();
2658
2659 23a193da Phil Davis
	for ($i = 0; $i < ob_get_level(); $i++) {
2660
		ob_end_flush();
2661
	}
2662 08fd5444 jim-p
	ob_implicit_flush(1);
2663 971de1f9 Renato Botelho
	set_single_sysctl("kern.geom.debugflags", "16");
2664 08fd5444 jim-p
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2665
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2666
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2667 2b5f276f jim-p
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2668 971de1f9 Renato Botelho
	set_single_sysctl("kern.geom.debugflags", "0");
2669 23a193da Phil Davis
	if ($status) {
2670 08fd5444 jim-p
		return false;
2671
	} else {
2672
		return true;
2673
	}
2674
}
2675 2b5f276f jim-p
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2676
	$tmppath = "/tmp/{$gslice}";
2677
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2678
2679 873c1701 Renato Botelho
	mkdir($tmppath);
2680 2b5f276f jim-p
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2681
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2682 873c1701 Renato Botelho
	copy("/etc/fstab", $fstabpath);
2683 2b5f276f jim-p
2684
	if (!file_exists($fstabpath)) {
2685
		$fstab = <<<EOF
2686 9b1a8d98 Ermal
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2687
/dev/ufs/cf /cf ufs ro,noatime 1 1
2688 2b5f276f jim-p
EOF;
2689 23a193da Phil Davis
		if (file_put_contents($fstabpath, $fstab)) {
2690 2b5f276f jim-p
			$status = true;
2691 23a193da Phil Davis
		} else {
2692 2b5f276f jim-p
			$status = false;
2693 23a193da Phil Davis
		}
2694 2b5f276f jim-p
	} else {
2695 84c82d3d doktornotor
		$status = exec("/usr/bin/sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2696 2b5f276f jim-p
	}
2697
	exec("/sbin/umount {$tmppath}");
2698 873c1701 Renato Botelho
	rmdir($tmppath);
2699 2b5f276f jim-p
2700
	return $status;
2701
}
2702 08fd5444 jim-p
function nanobsd_detect_slice_info() {
2703
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2704
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2705
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2706 a76c1c45 jim-p
2707 08fd5444 jim-p
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2708
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2709
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2710
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2711
2712
	// Detect which slice is active and set information.
2713 23a193da Phil Davis
	if (strstr($REAL_BOOT_DEVICE, "s1")) {
2714 4de8f7ba Phil Davis
		$SLICE = "2";
2715
		$OLDSLICE = "1";
2716
		$GLABEL_SLICE = "pfsense1";
2717
		$UFS_ID = "1";
2718
		$OLD_UFS_ID = "0";
2719 a76c1c45 jim-p
2720 08fd5444 jim-p
	} else {
2721 4de8f7ba Phil Davis
		$SLICE = "1";
2722
		$OLDSLICE = "2";
2723
		$GLABEL_SLICE = "pfsense0";
2724
		$UFS_ID = "0";
2725
		$OLD_UFS_ID = "1";
2726 08fd5444 jim-p
	}
2727 4de8f7ba Phil Davis
	$TOFLASH = "{$BOOT_DRIVE}s{$SLICE}";
2728
	$COMPLETE_PATH = "{$BOOT_DRIVE}s{$SLICE}a";
2729
	$COMPLETE_BOOT_PATH = "{$BOOT_DRIVE}s{$OLDSLICE}";
2730
	$BOOTFLASH = "{$BOOT_DRIVE}s{$OLDSLICE}";
2731 08fd5444 jim-p
}
2732 38080cc1 Scott Ullrich
2733 26c8cc72 jim-p
function nanobsd_friendly_slice_name($slicename) {
2734
	global $g;
2735
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2736
}
2737
2738 38080cc1 Scott Ullrich
function get_include_contents($filename) {
2739 5fa78adc Renato Botelho
	if (is_file($filename)) {
2740
		ob_start();
2741
		include $filename;
2742
		$contents = ob_get_contents();
2743
		ob_end_clean();
2744
		return $contents;
2745
	}
2746
	return false;
2747 38080cc1 Scott Ullrich
}
2748
2749 3ffa8318 Renato Botelho
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2750
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2751
 * size of the RRD xml dumps this is required.
2752
 * The reason we do not use it for pfSense is that it does not know about array fields
2753
 * which causes it to fail on array fields with single items. Possible Todo?
2754
 */
2755 086cf944 Phil Davis
function xml2array($contents, $get_attributes = 1, $priority = 'tag') {
2756 23a193da Phil Davis
	if (!function_exists('xml_parser_create')) {
2757 86c707f3 Darren Embry
		return array ();
2758
	}
2759
	$parser = xml_parser_create('');
2760
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2761
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2762
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2763
	xml_parse_into_struct($parser, trim($contents), $xml_values);
2764
	xml_parser_free($parser);
2765 23a193da Phil Davis
	if (!$xml_values) {
2766 86c707f3 Darren Embry
		return; //Hmm...
2767 23a193da Phil Davis
	}
2768 86c707f3 Darren Embry
	$xml_array = array ();
2769
	$parents = array ();
2770
	$opened_tags = array ();
2771
	$arr = array ();
2772
	$current = & $xml_array;
2773
	$repeated_tag_index = array ();
2774 23a193da Phil Davis
	foreach ($xml_values as $data) {
2775 86c707f3 Darren Embry
		unset ($attributes, $value);
2776
		extract($data);
2777
		$result = array ();
2778
		$attributes_data = array ();
2779 23a193da Phil Davis
		if (isset ($value)) {
2780
			if ($priority == 'tag') {
2781 86c707f3 Darren Embry
				$result = $value;
2782 23a193da Phil Davis
			} else {
2783 86c707f3 Darren Embry
				$result['value'] = $value;
2784 23a193da Phil Davis
			}
2785 86c707f3 Darren Embry
		}
2786 23a193da Phil Davis
		if (isset ($attributes) and $get_attributes) {
2787
			foreach ($attributes as $attr => $val) {
2788
				if ($priority == 'tag') {
2789 86c707f3 Darren Embry
					$attributes_data[$attr] = $val;
2790 23a193da Phil Davis
				} else {
2791 86c707f3 Darren Embry
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2792 23a193da Phil Davis
				}
2793 86c707f3 Darren Embry
			}
2794
		}
2795 23a193da Phil Davis
		if ($type == "open") {
2796 86c707f3 Darren Embry
			$parent[$level -1] = & $current;
2797 23a193da Phil Davis
			if (!is_array($current) or (!in_array($tag, array_keys($current)))) {
2798 86c707f3 Darren Embry
				$current[$tag] = $result;
2799 23a193da Phil Davis
				if ($attributes_data) {
2800 86c707f3 Darren Embry
					$current[$tag . '_attr'] = $attributes_data;
2801 23a193da Phil Davis
				}
2802 86c707f3 Darren Embry
				$repeated_tag_index[$tag . '_' . $level] = 1;
2803
				$current = & $current[$tag];
2804 23a193da Phil Davis
			} else {
2805
				if (isset ($current[$tag][0])) {
2806 86c707f3 Darren Embry
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2807
					$repeated_tag_index[$tag . '_' . $level]++;
2808 23a193da Phil Davis
				} else {
2809 86c707f3 Darren Embry
					$current[$tag] = array (
2810
						$current[$tag],
2811
						$result
2812
						);
2813
					$repeated_tag_index[$tag . '_' . $level] = 2;
2814 23a193da Phil Davis
					if (isset ($current[$tag . '_attr'])) {
2815 86c707f3 Darren Embry
						$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2816
						unset ($current[$tag . '_attr']);
2817
					}
2818
				}
2819
				$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2820
				$current = & $current[$tag][$last_item_index];
2821
			}
2822 23a193da Phil Davis
		} elseif ($type == "complete") {
2823
			if (!isset ($current[$tag])) {
2824 86c707f3 Darren Embry
				$current[$tag] = $result;
2825
				$repeated_tag_index[$tag . '_' . $level] = 1;
2826 23a193da Phil Davis
				if ($priority == 'tag' and $attributes_data) {
2827 86c707f3 Darren Embry
					$current[$tag . '_attr'] = $attributes_data;
2828 23a193da Phil Davis
				}
2829
			} else {
2830
				if (isset ($current[$tag][0]) and is_array($current[$tag])) {
2831 86c707f3 Darren Embry
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2832 23a193da Phil Davis
					if ($priority == 'tag' and $get_attributes and $attributes_data) {
2833 86c707f3 Darren Embry
						$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2834
					}
2835
					$repeated_tag_index[$tag . '_' . $level]++;
2836 23a193da Phil Davis
				} else {
2837 86c707f3 Darren Embry
					$current[$tag] = array (
2838
						$current[$tag],
2839
						$result
2840
						);
2841
					$repeated_tag_index[$tag . '_' . $level] = 1;
2842 23a193da Phil Davis
					if ($priority == 'tag' and $get_attributes) {
2843
						if (isset ($current[$tag . '_attr'])) {
2844 86c707f3 Darren Embry
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2845
							unset ($current[$tag . '_attr']);
2846
						}
2847 23a193da Phil Davis
						if ($attributes_data) {
2848 86c707f3 Darren Embry
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2849
						}
2850
					}
2851
					$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2852
				}
2853
			}
2854 23a193da Phil Davis
		} elseif ($type == 'close') {
2855 86c707f3 Darren Embry
			$current = & $parent[$level -1];
2856
		}
2857
	}
2858
	return ($xml_array);
2859 3ffa8318 Renato Botelho
}
2860
2861
function get_country_name($country_code) {
2862 23a193da Phil Davis
	if ($country_code != "ALL" && strlen($country_code) != 2) {
2863 3ffa8318 Renato Botelho
		return "";
2864 23a193da Phil Davis
	}
2865 3ffa8318 Renato Botelho
2866
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2867
	$country_names_contents = file_get_contents($country_names_xml);
2868
	$country_names = xml2array($country_names_contents);
2869
2870 23a193da Phil Davis
	if ($country_code == "ALL") {
2871 3ffa8318 Renato Botelho
		$country_list = array();
2872 23a193da Phil Davis
		foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2873
			$country_list[] = array(
2874
				"code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2875
				"name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])));
2876 3ffa8318 Renato Botelho
		}
2877
		return $country_list;
2878
	}
2879
2880
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2881
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2882
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2883
		}
2884
	}
2885
	return "";
2886
}
2887
2888 baaa8bb1 Erik Fonnesbeck
/* sort by interface only, retain the original order of rules that apply to
2889
   the same interface */
2890
function filter_rules_sort() {
2891
	global $config;
2892
2893
	/* mark each rule with the sequence number (to retain the order while sorting) */
2894 23a193da Phil Davis
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++) {
2895 baaa8bb1 Erik Fonnesbeck
		$config['filter']['rule'][$i]['seq'] = $i;
2896 23a193da Phil Davis
	}
2897 baaa8bb1 Erik Fonnesbeck
2898
	usort($config['filter']['rule'], "filter_rules_compare");
2899
2900
	/* strip the sequence numbers again */
2901 23a193da Phil Davis
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++) {
2902 baaa8bb1 Erik Fonnesbeck
		unset($config['filter']['rule'][$i]['seq']);
2903 23a193da Phil Davis
	}
2904 baaa8bb1 Erik Fonnesbeck
}
2905
function filter_rules_compare($a, $b) {
2906 23a193da Phil Davis
	if (isset($a['floating']) && isset($b['floating'])) {
2907 baaa8bb1 Erik Fonnesbeck
		return $a['seq'] - $b['seq'];
2908 23a193da Phil Davis
	} else if (isset($a['floating'])) {
2909 baaa8bb1 Erik Fonnesbeck
		return -1;
2910 23a193da Phil Davis
	} else if (isset($b['floating'])) {
2911 baaa8bb1 Erik Fonnesbeck
		return 1;
2912 23a193da Phil Davis
	} else if ($a['interface'] == $b['interface']) {
2913 cea355a5 Erik Fonnesbeck
		return $a['seq'] - $b['seq'];
2914 23a193da Phil Davis
	} else {
2915 baaa8bb1 Erik Fonnesbeck
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2916 23a193da Phil Davis
	}
2917 baaa8bb1 Erik Fonnesbeck
}
2918
2919 22dae853 Seth Mos
function generate_ipv6_from_mac($mac) {
2920
	$elements = explode(":", $mac);
2921 23a193da Phil Davis
	if (count($elements) <> 6) {
2922 22dae853 Seth Mos
		return false;
2923 23a193da Phil Davis
	}
2924 22dae853 Seth Mos
2925
	$i = 0;
2926 5aa28c86 Seth Mos
	$ipv6 = "fe80::";
2927 23a193da Phil Davis
	foreach ($elements as $byte) {
2928
		if ($i == 0) {
2929 4de8f7ba Phil Davis
			$hexadecimal = substr($byte, 1, 2);
2930 22dae853 Seth Mos
			$bitmap = base_convert($hexadecimal, 16, 2);
2931
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2932 4de8f7ba Phil Davis
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3, 4);
2933 22dae853 Seth Mos
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2934
		}
2935
		$ipv6 .= $byte;
2936 23a193da Phil Davis
		if ($i == 1) {
2937 22dae853 Seth Mos
			$ipv6 .= ":";
2938
		}
2939 23a193da Phil Davis
		if ($i == 3) {
2940 22dae853 Seth Mos
			$ipv6 .= ":";
2941
		}
2942 23a193da Phil Davis
		if ($i == 2) {
2943 22dae853 Seth Mos
			$ipv6 .= "ff:fe";
2944
		}
2945 5fa78adc Renato Botelho
2946 22dae853 Seth Mos
		$i++;
2947 5fa78adc Renato Botelho
	}
2948 fcdc8943 Seth Mos
	return $ipv6;
2949 22dae853 Seth Mos
}
2950 325e3163 Bill Marquette
2951 57f2840e Evgeny
/****f* pfsense-utils/load_mac_manufacturer_table
2952
 * NAME
2953
 *   load_mac_manufacturer_table
2954
 * INPUTS
2955
 *   none
2956
 * RESULT
2957
 *   returns associative array with MAC-Manufacturer pairs
2958
 ******/
2959
function load_mac_manufacturer_table() {
2960
	/* load MAC-Manufacture data from the file */
2961 62a29fe3 Ermal
	$macs = false;
2962 23a193da Phil Davis
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes")) {
2963 62a29fe3 Ermal
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2964 23a193da Phil Davis
	}
2965
	if ($macs) {
2966
		foreach ($macs as $line) {
2967
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)) {
2968 4450527f Evgeny
				/* store values like this $mac_man['000C29']='VMware' */
2969 4de8f7ba Phil Davis
				$mac_man["$matches[1]"] = $matches[2];
2970 57f2840e Evgeny
			}
2971
		}
2972 5fa78adc Renato Botelho
		return $mac_man;
2973 23a193da Phil Davis
	} else {
2974 57f2840e Evgeny
		return -1;
2975 23a193da Phil Davis
	}
2976 57f2840e Evgeny
2977
}
2978
2979 474f36d1 Scott Ullrich
/****f* pfsense-utils/is_ipaddr_configured
2980
 * NAME
2981
 *   is_ipaddr_configured
2982
 * INPUTS
2983
 *   IP Address to check.
2984 4665dbdd Renato Botelho
 *   If ignore_if is a VIP (not carp), vip array index is passed after string _virtualip
2985 160d285a jim-p
 *   check_localip - if true then also check for matches with PPTP and L2TP addresses
2986 3490b8dd Phil Davis
 *   check_subnets - if true then check if the given ipaddr is contained anywhere in the subnet of any other configured IP address
2987
 *   cidrprefix - the CIDR prefix (16, 20, 24, 64...) of ipaddr.
2988 086cf944 Phil Davis
 *     If check_subnets is true and cidrprefix is specified,
2989 3490b8dd Phil Davis
 *     then check if the ipaddr/cidrprefix subnet overlaps the subnet of any other configured IP address
2990 474f36d1 Scott Ullrich
 * RESULT
2991 3490b8dd Phil Davis
 *   returns true if the IP Address is configured and present on this device or overlaps a configured subnet.
2992 474f36d1 Scott Ullrich
*/
2993 3490b8dd Phil Davis
function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false, $cidrprefix = "") {
2994
	if (count(where_is_ipaddr_configured($ipaddr, $ignore_if, $check_localip, $check_subnets, $cidrprefix))) {
2995
		return true;
2996
	}
2997
	return false;
2998
}
2999
3000
/****f* pfsense-utils/where_is_ipaddr_configured
3001
 * NAME
3002
 *   where_is_ipaddr_configured
3003
 * INPUTS
3004
 *   IP Address to check.
3005
 *   If ignore_if is a VIP (not carp), vip array index is passed after string _virtualip
3006 160d285a jim-p
 *   check_localip - if true then also check for matches with PPTP and L2TP addresses
3007 3490b8dd Phil Davis
 *   check_subnets - if true then check if the given ipaddr is contained anywhere in the subnet of any other configured IP address
3008
 *   cidrprefix - the CIDR prefix (16, 20, 24, 64...) of ipaddr.
3009 086cf944 Phil Davis
 *     If check_subnets is true and cidrprefix is specified,
3010 3490b8dd Phil Davis
 *     then check if the ipaddr/cidrprefix subnet overlaps the subnet of any other configured IP address
3011
 * RESULT
3012
 *   Returns an array of the interfaces 'if' plus IP address or subnet 'ip_or_subnet' that match or overlap the IP address to check.
3013
 *   If there are no matches then an empty array is returned.
3014
*/
3015
function where_is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false, $cidrprefix = "") {
3016 e6c60013 Renato Botelho
	global $config;
3017
3018 3490b8dd Phil Davis
	$where_configured = array();
3019
3020 4665dbdd Renato Botelho
	$pos = strpos($ignore_if, '_virtualip');
3021
	if ($pos !== false) {
3022
		$ignore_vip_id = substr($ignore_if, $pos+10);
3023
		$ignore_vip_if = substr($ignore_if, 0, $pos);
3024
	} else {
3025
		$ignore_vip_id = -1;
3026
		$ignore_vip_if = $ignore_if;
3027
	}
3028
3029 1e5da31d Ermal
	$isipv6 = is_ipaddrv6($ipaddr);
3030
3031 c528a112 Phil Davis
	if ($isipv6) {
3032
		$ipaddr = text_to_compressed_ip6($ipaddr);
3033
	}
3034
3035 e6c60013 Renato Botelho
	if ($check_subnets) {
3036 3490b8dd Phil Davis
		$cidrprefix = intval($cidrprefix);
3037
		if ($isipv6) {
3038
			if (($cidrprefix < 1) || ($cidrprefix > 128)) {
3039
				$cidrprefix = 128;
3040
			}
3041
		} else {
3042
			if (($cidrprefix < 1) || ($cidrprefix > 32)) {
3043
				$cidrprefix = 32;
3044
			}
3045
		}
3046 e6c60013 Renato Botelho
		$iflist = get_configured_interface_list();
3047
		foreach ($iflist as $if => $ifname) {
3048 23a193da Phil Davis
			if ($ignore_if == $if) {
3049 e6c60013 Renato Botelho
				continue;
3050 23a193da Phil Davis
			}
3051 2c98a935 Renato Botelho
3052 3490b8dd Phil Davis
			if ($isipv6) {
3053
				$if_ipv6 = get_interface_ipv6($if);
3054
				$if_snbitsv6 = get_interface_subnetv6($if);
3055
				if ($if_ipv6 && $if_snbitsv6 && check_subnetsv6_overlap($ipaddr, $cidrprefix, $if_ipv6, $if_snbitsv6)) {
3056
					$where_entry = array();
3057
					$where_entry['if'] = $if;
3058
					$where_entry['ip_or_subnet'] = get_interface_ipv6($if) . "/" . get_interface_subnetv6($if);
3059
					$where_configured[] = $where_entry;
3060
				}
3061 1e5da31d Ermal
			} else {
3062 3490b8dd Phil Davis
				$if_ipv4 = get_interface_ip($if);
3063
				$if_snbitsv4 = get_interface_subnet($if);
3064
				if ($if_ipv4 && $if_snbitsv4 && check_subnets_overlap($ipaddr, $cidrprefix, $if_ipv4, $if_snbitsv4)) {
3065
					$where_entry = array();
3066
					$where_entry['if'] = $if;
3067
					$where_entry['ip_or_subnet'] = get_interface_ip($if) . "/" . get_interface_subnet($if);
3068
					$where_configured[] = $where_entry;
3069 4de8f7ba Phil Davis
				}
3070 23a193da Phil Davis
			}
3071 e6c60013 Renato Botelho
		}
3072
	} else {
3073 3490b8dd Phil Davis
		if ($isipv6) {
3074 2c98a935 Renato Botelho
			$interface_list_ips = get_configured_ipv6_addresses();
3075 23a193da Phil Davis
		} else {
3076 2c98a935 Renato Botelho
			$interface_list_ips = get_configured_ip_addresses();
3077 23a193da Phil Davis
		}
3078 2c98a935 Renato Botelho
3079 23a193da Phil Davis
		foreach ($interface_list_ips as $if => $ilips) {
3080
			if ($ignore_if == $if) {
3081 e6c60013 Renato Botelho
				continue;
3082 23a193da Phil Davis
			}
3083
			if (strcasecmp($ipaddr, $ilips) == 0) {
3084 3490b8dd Phil Davis
				$where_entry = array();
3085
				$where_entry['if'] = $if;
3086
				$where_entry['ip_or_subnet'] = $ilips;
3087
				$where_configured[] = $where_entry;
3088 23a193da Phil Davis
			}
3089 e6c60013 Renato Botelho
		}
3090 5fa78adc Renato Botelho
	}
3091 a1613b62 Renato Botelho
3092 e6c60013 Renato Botelho
	if ($check_localip) {
3093 5e82a83a Phil Davis
		if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, text_to_compressed_ip6($config['l2tp']['localip'])) == 0)) {
3094 3490b8dd Phil Davis
			$where_entry = array();
3095
			$where_entry['if'] = 'l2tp';
3096
			$where_entry['ip_or_subnet'] = $config['l2tp']['localip'];
3097
			$where_configured[] = $where_entry;
3098 23a193da Phil Davis
		}
3099 a1613b62 Renato Botelho
	}
3100
3101 3490b8dd Phil Davis
	return $where_configured;
3102 474f36d1 Scott Ullrich
}
3103
3104 e4a8ed97 Scott Ullrich
/****f* pfsense-utils/pfSense_handle_custom_code
3105
 * NAME
3106
 *   pfSense_handle_custom_code
3107
 * INPUTS
3108
 *   directory name to process
3109
 * RESULT
3110
 *   globs the directory and includes the files
3111
 */
3112 d65962a7 Scott Ullrich
function pfSense_handle_custom_code($src_dir) {
3113 5fa78adc Renato Botelho
	// Allow extending of the nat edit page and include custom input validation
3114 23a193da Phil Davis
	if (is_dir("$src_dir")) {
3115 3dbceb92 Scott Ullrich
		$cf = glob($src_dir . "/*.inc");
3116 23a193da Phil Davis
		foreach ($cf as $nf) {
3117
			if ($nf == "." || $nf == "..") {
3118 d65962a7 Scott Ullrich
				continue;
3119 23a193da Phil Davis
			}
3120 d65962a7 Scott Ullrich
			// Include the extra handler
3121 6dfb6b27 Phil Davis
			include_once("$nf");
3122 d65962a7 Scott Ullrich
		}
3123
	}
3124
}
3125
3126 ceecd29b Renato Botelho
function set_language() {
3127
	global $config, $g;
3128
3129
	if (!empty($config['system']['language'])) {
3130
		$lang = $config['system']['language'];
3131
	} elseif (!empty($g['language'])) {
3132
		$lang = $g['language'];
3133
	}
3134
	$lang .= ".UTF-8";
3135
3136
	putenv("LANG={$lang}");
3137 53c25dec Renato Botelho
	setlocale(LC_ALL, $lang);
3138
	textdomain("pfSense");
3139
	bindtextdomain("pfSense", "/usr/local/share/locale");
3140
	bind_textdomain_codeset("pfSense", $lang);
3141 3e139f90 Vinicius Coque
}
3142
3143
function get_locale_list() {
3144
	$locales = array(
3145
		"en_US" => gettext("English"),
3146 2e2eb012 Vinicius Coque
		"pt_BR" => gettext("Portuguese (Brazil)"),
3147 f079b676 technical50
		"tr" => gettext("Turkish"),
3148 3e139f90 Vinicius Coque
	);
3149
	asort($locales);
3150
	return $locales;
3151
}
3152 20a7cb15 smos
3153
function return_hex_ipv4($ipv4) {
3154 23a193da Phil Davis
	if (!is_ipaddrv4($ipv4)) {
3155 20a7cb15 smos
		return(false);
3156 23a193da Phil Davis
	}
3157 5fa78adc Renato Botelho
3158 20a7cb15 smos
	/* we need the hex form of the interface IPv4 address */
3159
	$ip4arr = explode(".", $ipv4);
3160 733c6f89 Ermal
	return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3]));
3161 20a7cb15 smos
}
3162
3163
function convert_ipv6_to_128bit($ipv6) {
3164 23a193da Phil Davis
	if (!is_ipaddrv6($ipv6)) {
3165 20a7cb15 smos
		return(false);
3166 23a193da Phil Davis
	}
3167 20a7cb15 smos
3168
	$ip6arr = array();
3169
	$ip6prefix = Net_IPv6::uncompress($ipv6);
3170
	$ip6arr = explode(":", $ip6prefix);
3171
	/* binary presentation of the prefix for all 128 bits. */
3172
	$ip6prefixbin = "";
3173 23a193da Phil Davis
	foreach ($ip6arr as $element) {
3174 20a7cb15 smos
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
3175
	}
3176
	return($ip6prefixbin);
3177
}
3178
3179
function convert_128bit_to_ipv6($ip6bin) {
3180 23a193da Phil Davis
	if (strlen($ip6bin) <> 128) {
3181 20a7cb15 smos
		return(false);
3182 23a193da Phil Davis
	}
3183 20a7cb15 smos
3184
	$ip6arr = array();
3185
	$ip6binarr = array();
3186
	$ip6binarr = str_split($ip6bin, 16);
3187 23a193da Phil Davis
	foreach ($ip6binarr as $binpart) {
3188 20a7cb15 smos
		$ip6arr[] = dechex(bindec($binpart));
3189 23a193da Phil Davis
	}
3190 5050b792 Phil Davis
	$ip6addr = text_to_compressed_ip6(implode(":", $ip6arr));
3191 20a7cb15 smos
3192
	return($ip6addr);
3193
}
3194
3195 8b198c64 smos
3196
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
3197
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
3198
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
3199
/* 6to4 is 16 bits, e.g. 65535 */
3200
function calculate_ipv6_delegation_length($if) {
3201
	global $config;
3202
3203 23a193da Phil Davis
	if (!is_array($config['interfaces'][$if])) {
3204 8b198c64 smos
		return false;
3205 23a193da Phil Davis
	}
3206 8b198c64 smos
3207 23a193da Phil Davis
	switch ($config['interfaces'][$if]['ipaddrv6']) {
3208 8b198c64 smos
		case "6to4":
3209
			$pdlen = 16;
3210
			break;
3211
		case "6rd":
3212
			$rd6cfg = $config['interfaces'][$if];
3213
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
3214
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
3215
			break;
3216
		case "dhcp6":
3217
			$dhcp6cfg = $config['interfaces'][$if];
3218
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
3219
			break;
3220
		default:
3221
			$pdlen = 0;
3222
			break;
3223
	}
3224
	return($pdlen);
3225
}
3226 d23e157a smos
3227 a3d07046 Renato Botelho
function merge_ipv6_delegated_prefix($prefix, $suffix, $len = 64) {
3228
	$prefix = Net_IPv6::uncompress($prefix, true);
3229
	$suffix = Net_IPv6::uncompress($suffix, true);
3230
3231
	/*
3232
	 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
3233
	 *                ^^^^ ^
3234
	 *                |||| \-> 64
3235
	 *                |||\---> 63, 62, 61, 60
3236
	 *                ||\----> 56
3237
	 *                |\-----> 52
3238
	 *                \------> 48
3239
	 */
3240
3241
	switch ($len) {
3242
	case 48:
3243
		$prefix_len = 15;
3244
		break;
3245
	case 52:
3246
		$prefix_len = 16;
3247
		break;
3248
	case 56:
3249
		$prefix_len = 17;
3250
		break;
3251 145105bb Phil Davis
	case 59:
3252 a3d07046 Renato Botelho
	case 60:
3253
		$prefix_len = 18;
3254
		break;
3255
	/*
3256
	 * XXX 63, 62 and 61 should use 18 but PD can change and if
3257
	 * we let user chose this bit it can end up out of PD network
3258
	 *
3259
	 * Leave this with 20 for now until we find a way to let user
3260
	 * chose it. The side-effect is users with PD with one of these
3261
	 * lengths will not be able to setup DHCP server range for full
3262
	 * PD size, only for last /64 network
3263
	 */
3264
	case 63:
3265
	case 62:
3266
	case 61:
3267
	default:
3268
		$prefix_len = 20;
3269
		break;
3270
	}
3271
3272 5050b792 Phil Davis
	return text_to_compressed_ip6(substr($prefix, 0, $prefix_len) .
3273 a3d07046 Renato Botelho
	    substr($suffix, $prefix_len));
3274 2bf455ca Renato Botelho
}
3275
3276 6c8beed3 Renato Botelho
function dhcpv6_pd_str_help($pdlen) {
3277
	$result = '';
3278
3279
	switch ($pdlen) {
3280
	case 48:
3281
		$result = '::xxxx:xxxx:xxxx:xxxx:xxxx';
3282
		break;
3283
	case 52:
3284
		$result = '::xxx:xxxx:xxxx:xxxx:xxxx';
3285
		break;
3286
	case 56:
3287
		$result = '::xx:xxxx:xxxx:xxxx:xxxx';
3288
		break;
3289 145105bb Phil Davis
	case 59:
3290 6c8beed3 Renato Botelho
	case 60:
3291
		$result = '::x:xxxx:xxxx:xxxx:xxxx';
3292
		break;
3293
	/*
3294 564dc6fa Phil Davis
	 * XXX 63, 62 and 61 should use same mask as 60 but if
3295
	 * we let the user choose this bit it can end up out of PD network
3296 6c8beed3 Renato Botelho
	 *
3297 564dc6fa Phil Davis
	 * Leave this with the same as 64 for now until we find a way to
3298
	 * let the user choose it. The side-effect is users with PD with one
3299
	 * of these lengths will not be able to setup DHCP server ranges
3300 6c8beed3 Renato Botelho
	 * for full PD size, only for last /64 network
3301
	 */
3302
	case 61:
3303
	case 62:
3304
	case 63:
3305
	case 64:
3306 564dc6fa Phil Davis
	default:
3307 6c8beed3 Renato Botelho
		$result = '::xxxx:xxxx:xxxx:xxxx';
3308
		break;
3309
	}
3310
3311
	return $result;
3312
}
3313
3314 d23e157a smos
function huawei_rssi_to_string($rssi) {
3315
	$dbm = array();
3316
	$i = 0;
3317 145cc518 smos
	$dbstart = -113;
3318 23a193da Phil Davis
	while ($i < 32) {
3319 145cc518 smos
		$dbm[$i] = $dbstart + ($i * 2);
3320 d23e157a smos
		$i++;
3321
	}
3322
	$percent = round(($rssi / 31) * 100);
3323 145cc518 smos
	$string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%";
3324 d23e157a smos
	return $string;
3325
}
3326
3327
function huawei_mode_to_string($mode, $submode) {
3328 e8c516a0 Phil Davis
	$modes[0] = gettext("None");
3329 5fa78adc Renato Botelho
	$modes[1] = "AMPS";
3330 d23e157a smos
	$modes[2] = "CDMA";
3331
	$modes[3] = "GSM/GPRS";
3332
	$modes[4] = "HDR";
3333
	$modes[5] = "WCDMA";
3334 5fa78adc Renato Botelho
	$modes[6] = "GPS";
3335 d23e157a smos
3336 e8c516a0 Phil Davis
	$submodes[0] = gettext("No Service");
3337 d23e157a smos
	$submodes[1] = "GSM";
3338
	$submodes[2] = "GPRS";
3339
	$submodes[3] = "EDGE";
3340
	$submodes[4] = "WCDMA";
3341
	$submodes[5] = "HSDPA";
3342
	$submodes[6] = "HSUPA";
3343 e313da37 smos
	$submodes[7] = "HSDPA+HSUPA";
3344 d23e157a smos
	$submodes[8] = "TD-SCDMA";
3345
	$submodes[9] = "HSPA+";
3346 e8c516a0 Phil Davis
	$string = "{$modes[$mode]}, {$submodes[$submode]} " . gettext("Mode");
3347 d23e157a smos
	return $string;
3348
}
3349
3350
function huawei_service_to_string($state) {
3351 e8c516a0 Phil Davis
	$modes[0] = gettext("No Service");
3352
	$modes[1] = gettext("Restricted Service");
3353
	$modes[2] = gettext("Valid Service");
3354
	$modes[3] = gettext("Restricted Regional Service");
3355
	$modes[4] = gettext("Powersaving Service");
3356
	$string = $modes[$state];
3357 d23e157a smos
	return $string;
3358
}
3359
3360
function huawei_simstate_to_string($state) {
3361 e8c516a0 Phil Davis
	$modes[0] = gettext("Invalid SIM/locked State");
3362
	$modes[1] = gettext("Valid SIM State");
3363
	$modes[2] = gettext("Invalid SIM CS State");
3364
	$modes[3] = gettext("Invalid SIM PS State");
3365
	$modes[4] = gettext("Invalid SIM CS/PS State");
3366
	$modes[255] = gettext("Missing SIM State");
3367
	$string = $modes[$state];
3368 d23e157a smos
	return $string;
3369
}
3370 4adf752c smos
3371
function zte_rssi_to_string($rssi) {
3372
	return huawei_rssi_to_string($rssi);
3373
}
3374
3375
function zte_mode_to_string($mode, $submode) {
3376 e8c516a0 Phil Davis
	$modes[0] = gettext("No Service");
3377
	$modes[1] = gettext("Limited Service");
3378 4adf752c smos
	$modes[2] = "GPRS";
3379
	$modes[3] = "GSM";
3380
	$modes[4] = "UMTS";
3381
	$modes[5] = "EDGE";
3382 5fa78adc Renato Botelho
	$modes[6] = "HSDPA";
3383 4adf752c smos
3384
	$submodes[0] = "CS_ONLY";
3385
	$submodes[1] = "PS_ONLY";
3386
	$submodes[2] = "CS_PS";
3387
	$submodes[3] = "CAMPED";
3388 e8c516a0 Phil Davis
	$string = "{$modes[$mode]}, {$submodes[$submode]} " . gettext("Mode");
3389 4adf752c smos
	return $string;
3390
}
3391
3392 e8c516a0 Phil Davis
function zte_service_to_string($service) {
3393
	$modes[0] = gettext("Initializing Service");
3394
	$modes[1] = gettext("Network Lock error Service");
3395
	$modes[2] = gettext("Network Locked Service");
3396
	$modes[3] = gettext("Unlocked or correct MCC/MNC Service");
3397
	$string = $modes[$service];
3398 4adf752c smos
	return $string;
3399
}
3400
3401
function zte_simstate_to_string($state) {
3402 e8c516a0 Phil Davis
	$modes[0] = gettext("No action State");
3403
	$modes[1] = gettext("Network lock State");
3404
	$modes[2] = gettext("(U)SIM card lock State");
3405
	$modes[3] = gettext("Network Lock and (U)SIM card Lock State");
3406
	$string = $modes[$state];
3407 4adf752c smos
	return $string;
3408
}
3409 e9ab2ddb smos
3410
function get_configured_pppoe_server_interfaces() {
3411
	global $config;
3412
	$iflist = array();
3413
	if (is_array($config['pppoes']['pppoe'])) {
3414 23a193da Phil Davis
		foreach ($config['pppoes']['pppoe'] as $pppoe) {
3415 e9ab2ddb smos
			if ($pppoe['mode'] == "server") {
3416
				$int = "poes". $pppoe['pppoeid'];
3417
				$iflist[$int] = strtoupper($int);
3418
			}
3419
		}
3420
	}
3421
	return $iflist;
3422
}
3423
3424
function get_pppoes_child_interfaces($ifpattern) {
3425
	$if_arr = array();
3426 23a193da Phil Davis
	if ($ifpattern == "") {
3427 e9ab2ddb smos
		return;
3428 23a193da Phil Davis
	}
3429 e9ab2ddb smos
3430 84c82d3d doktornotor
	exec("/sbin/ifconfig", $out, $ret);
3431 23a193da Phil Davis
	foreach ($out as $line) {
3432
		if (preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) {
3433 e9ab2ddb smos
			$if_arr[] = $match[1];
3434
		}
3435
	}
3436
	return $if_arr;
3437
3438
}
3439
3440 331166a8 PiBa-NL
/****f* pfsense-utils/pkg_call_plugins
3441
 * NAME
3442
 *   pkg_call_plugins
3443
 * INPUTS
3444
 *   $plugin_type value used to search in package configuration if the plugin is used, also used to create the function name
3445
 *   $plugin_params parameters to pass to the plugin function for passing multiple parameters a array can be used.
3446
 * RESULT
3447
 *   returns associative array results from the plugin calls for each package
3448
 * NOTES
3449
 *   This generic function can be used to notify or retrieve results from functions that are defined in packages.
3450
 ******/
3451
function pkg_call_plugins($plugin_type, $plugin_params) {
3452 eaee3af6 PiBa-NL
	global $g, $config;
3453
	$results = array();
3454 23a193da Phil Davis
	if (!is_array($config['installedpackages']['package'])) {
3455 331166a8 PiBa-NL
		return $results;
3456 23a193da Phil Davis
	}
3457 eaee3af6 PiBa-NL
	foreach ($config['installedpackages']['package'] as $package) {
3458 23a193da Phil Davis
		if (!file_exists("/usr/local/pkg/" . $package['configurationfile'])) {
3459 eaee3af6 PiBa-NL
			continue;
3460 23a193da Phil Davis
		}
3461 eaee3af6 PiBa-NL
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
3462 4de8f7ba Phil Davis
		$pkgname = substr(reverse_strrchr($package['configurationfile'], "."), 0, -1);
3463 23a193da Phil Davis
		if (is_array($pkg_config['plugins']['item'])) {
3464 3fe73243 PiBa-NL
			foreach ($pkg_config['plugins']['item'] as $plugin) {
3465 331166a8 PiBa-NL
				if ($plugin['type'] == $plugin_type) {
3466 23a193da Phil Davis
					if (file_exists($pkg_config['include_file'])) {
3467 eaee3af6 PiBa-NL
						require_once($pkg_config['include_file']);
3468 23a193da Phil Davis
					} else {
3469 eaee3af6 PiBa-NL
						continue;
3470 23a193da Phil Davis
					}
3471 eaee3af6 PiBa-NL
					$plugin_function = $pkgname . '_'. $plugin_type;
3472 c42117c1 PiBa-NL
					$results[$pkgname] = call_user_func($plugin_function, $plugin_params);
3473 eaee3af6 PiBa-NL
				}
3474
			}
3475 23a193da Phil Davis
		}
3476 eaee3af6 PiBa-NL
	}
3477
	return $results;
3478
}
3479
3480 bf1a013f NOYB
function restore_aliastables() {
3481
	global $g, $config;
3482
3483
	$dbpath = "{$g['vardb_path']}/aliastables/";
3484
3485
	/* restore the alias tables, if we have them */
3486
	$files = glob("{$g['cf_conf_path']}/RAM_Disk_Store{$dbpath}*.tgz");
3487
	if (count($files)) {
3488
		echo "Restoring alias tables...";
3489
		foreach ($files as $file) {
3490
			if (file_exists($file)) {
3491
				$aliastablesrestore = "";
3492
				$aliastablesreturn = "";
3493
				exec("cd /;LANG=C /usr/bin/tar -xzf {$file} 2>&1", $aliastablesrestore, $aliastablesreturn);
3494
				$aliastablesrestore = implode(" ", $aliastablesrestore);
3495
				if ($aliastablesreturn <> 0) {
3496
					log_error(sprintf(gettext('Alias table restore failed exited with %1$s, the error is: %2$s %3$s%4$s'), $aliastablesreturn, $aliastablesrestore, $file, "\n"));
3497
				} else {
3498
					log_error(sprintf(gettext('Alias table restore succeeded exited with %1$s, the result is: %2$s %3$s%4$s'), $aliastablesreturn, $aliastablesrestore, $dbpath.basename($file, ".tgz"), "\n"));
3499
				}
3500
			}
3501
			/* If this backup is still there on a full install, but we aren't going to use ram disks, remove the archive since this is a transition. */
3502
			if (($g['platform'] == $g['product_name']) && !isset($config['system']['use_mfs_tmpvar'])) {
3503
				unlink_if_exists("{$file}");
3504
			}
3505
		}
3506
		echo "done.\n";
3507
		return true;
3508
	}
3509
	return false;
3510
}
3511
3512 4c17e45f Steve Beaver
// Convert IPv6 addresses to lower case
3513
function addrtolower($ip) {
3514
	if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
3515
		return(strtolower($ip));
3516
	} else {
3517
		return($ip);
3518
	}
3519
}
3520 58005e52 jim-p
?>