Project

General

Profile

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