Project

General

Profile

Download (16.2 KB) Statistics
| Branch: | Tag: | Revision:
1 f9db3cda Seth Mos
<?php /* $Id$ */ /*
2 5b237745 Scott Ullrich
	util.inc
3
	part of m0n0wall (http://m0n0.ch/wall)
4 98bbf05a Scott Ullrich
5 5b237745 Scott Ullrich
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
6
	All rights reserved.
7 98bbf05a Scott Ullrich
8 5b237745 Scott Ullrich
	Redistribution and use in source and binary forms, with or without
9
	modification, are permitted provided that the following conditions are met:
10 98bbf05a Scott Ullrich
11 5b237745 Scott Ullrich
	1. Redistributions of source code must retain the above copyright notice,
12
	   this list of conditions and the following disclaimer.
13 98bbf05a Scott Ullrich
14 5b237745 Scott Ullrich
	2. Redistributions in binary form must reproduce the above copyright
15
	   notice, this list of conditions and the following disclaimer in the
16
	   documentation and/or other materials provided with the distribution.
17 98bbf05a Scott Ullrich
18 5b237745 Scott Ullrich
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
19
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
20
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
22
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
	POSSIBILITY OF SUCH DAMAGE.
28
*/
29
30
/* kill a process by pid file */
31
function killbypid($pidfile) {
32
	sigkillbypid($pidfile, "TERM");
33
}
34
35 53aca1fd Scott Ullrich
function isvalidpid($pid) {
36
	$running = `ps -p $pid | wc -l`;
37
	if(intval($running) > 1)
38
		return true;
39
	else 
40
		return false;
41
}
42
43
function isvalidproc($proc) {
44
	$running = `ps awux | grep $proc | grep -v grep | wc -l`;
45
	if(intval($running) > 1)
46
		return true;
47
	else 
48
		return false;
49
}
50
51 5b237745 Scott Ullrich
/* sigkill a process by pid file */
52 53aca1fd Scott Ullrich
/* return 1 for success and 0 for a failure */
53 5b237745 Scott Ullrich
function sigkillbypid($pidfile, $sig) {
54 53aca1fd Scott Ullrich
	if (is_file($pidfile)) {
55 9d59c08f Scott Ullrich
		$pid = trim(file_get_contents($pidfile));
56 53aca1fd Scott Ullrich
		if(isvalidpid($pid))
57 48e7db91 Seth Mos
			return mwexec("/bin/kill -s $sig {$pid}", true);
58 5b237745 Scott Ullrich
	}
59 53aca1fd Scott Ullrich
	return 0;
60
}
61
62
/* kill a process by name */
63
function sigkillbyname($procname, $sig) {
64
	if(isvalidproc($procname))
65 73239086 Seth Mos
		return mwexec("/usr/bin/killall -{$sig} " . escapeshellarg($procname), true);
66 5b237745 Scott Ullrich
}
67
68
/* kill a process by name */
69
function killbyname($procname) {
70 53aca1fd Scott Ullrich
	if(isvalidproc($procname))
71
		mwexec("/usr/bin/killall " . escapeshellarg($procname));
72 5b237745 Scott Ullrich
}
73
74
/* return the subnet address given a host address and a subnet bit count */
75
function gen_subnet($ipaddr, $bits) {
76
	if (!is_ipaddr($ipaddr) || !is_numeric($bits))
77
		return "";
78 98bbf05a Scott Ullrich
79 5b237745 Scott Ullrich
	return long2ip(ip2long($ipaddr) & gen_subnet_mask_long($bits));
80
}
81
82
/* return the highest (broadcast) address in the subnet given a host address and a subnet bit count */
83
function gen_subnet_max($ipaddr, $bits) {
84
	if (!is_ipaddr($ipaddr) || !is_numeric($bits))
85
		return "";
86 98bbf05a Scott Ullrich
87 5b237745 Scott Ullrich
	return long2ip(ip2long($ipaddr) | ~gen_subnet_mask_long($bits));
88
}
89
90
/* returns a subnet mask (long given a bit count) */
91
function gen_subnet_mask_long($bits) {
92
	$sm = 0;
93
	for ($i = 0; $i < $bits; $i++) {
94
		$sm >>= 1;
95
		$sm |= 0x80000000;
96
	}
97
	return $sm;
98
}
99
100
/* same as above but returns a string */
101
function gen_subnet_mask($bits) {
102
	return long2ip(gen_subnet_mask_long($bits));
103
}
104
105
function is_numericint($arg) {
106
	return (preg_match("/[^0-9]/", $arg) ? false : true);
107
}
108
109
/* returns true if $ipaddr is a valid dotted IPv4 address */
110
function is_ipaddr($ipaddr) {
111
	if (!is_string($ipaddr))
112
		return false;
113 98bbf05a Scott Ullrich
114 5b237745 Scott Ullrich
	$ip_long = ip2long($ipaddr);
115
	$ip_reverse = long2ip($ip_long);
116 98bbf05a Scott Ullrich
117 5b237745 Scott Ullrich
	if ($ipaddr == $ip_reverse)
118
		return true;
119
	else
120
		return false;
121
}
122
123
/* returns true if $ipaddr is a valid dotted IPv4 address or an alias thereof */
124
function is_ipaddroralias($ipaddr) {
125 3154d7ed Colin Smith
126 5b64aa38 Scott Ullrich
	global $aliastable, $config;
127
128 07168cc3 Bill Marquette
	if(is_array($config['aliases']['alias'])) {
129 55e0e4e5 Scott Ullrich
		foreach($config['aliases']['alias'] as $alias) {
130
			if($alias['name'] == $ipaddr)
131
				return true;
132
		}
133 8dbd4c3a Scott Ullrich
	}
134 98bbf05a Scott Ullrich
135 5b237745 Scott Ullrich
	if (isset($aliastable[$ipaddr]) && is_ipaddr($aliastable[$ipaddr]))
136
		return true;
137
	else
138
		return is_ipaddr($ipaddr);
139 b8014f9d Scott Ullrich
140 5b237745 Scott Ullrich
}
141
142
/* returns true if $ipaddr is a valid dotted IPv4 address or any alias */
143
function is_ipaddroranyalias($ipaddr) {
144 98bbf05a Scott Ullrich
145 5b237745 Scott Ullrich
	global $aliastable;
146 98bbf05a Scott Ullrich
147 5b237745 Scott Ullrich
	if (isset($aliastable[$ipaddr]))
148
		return true;
149
	else
150
		return is_ipaddr($ipaddr);
151
}
152
153
/* returns true if $subnet is a valid subnet in CIDR format */
154
function is_subnet($subnet) {
155
	if (!is_string($subnet))
156
		return false;
157 98bbf05a Scott Ullrich
158 5b237745 Scott Ullrich
	list($hp,$np) = explode('/', $subnet);
159 98bbf05a Scott Ullrich
160 5b237745 Scott Ullrich
	if (!is_ipaddr($hp))
161
		return false;
162 98bbf05a Scott Ullrich
163 5b237745 Scott Ullrich
	if (!is_numeric($np) || ($np < 1) || ($np > 32))
164
		return false;
165 98bbf05a Scott Ullrich
166 5b237745 Scott Ullrich
	return true;
167
}
168
169
/* returns true if $subnet is a valid subnet in CIDR format or an alias thereof */
170
function is_subnetoralias($subnet) {
171 98bbf05a Scott Ullrich
172 5b237745 Scott Ullrich
	global $aliastable;
173 98bbf05a Scott Ullrich
174 5b237745 Scott Ullrich
	if (isset($aliastable[$subnet]) && is_subnet($aliastable[$subnet]))
175
		return true;
176
	else
177
		return is_subnet($subnet);
178
}
179
180
/* returns true if $hostname is a valid hostname */
181
function is_hostname($hostname) {
182
	if (!is_string($hostname))
183
		return false;
184 98bbf05a Scott Ullrich
185 161a01bd Scott Ullrich
	if (preg_match("/^([_a-z0-9\-]+\.?)+$/i", $hostname))
186 5b237745 Scott Ullrich
		return true;
187
	else
188
		return false;
189
}
190
191
/* returns true if $domain is a valid domain name */
192
function is_domain($domain) {
193
	if (!is_string($domain))
194
		return false;
195 98bbf05a Scott Ullrich
196 856887a3 Scott Ullrich
	if (preg_match("/^([a-z0-9\-]+\.?)+$/i", $domain))
197 5b237745 Scott Ullrich
		return true;
198
	else
199
		return false;
200
}
201
202
/* returns true if $uname is a valid DynDNS username */
203
function is_dyndns_username($uname) {
204
	if (!is_string($uname))
205
		return false;
206 98bbf05a Scott Ullrich
207 5b237745 Scott Ullrich
	if (preg_match("/[^a-z0-9\-.@_]/i", $uname))
208
		return false;
209
	else
210
		return true;
211
}
212
213
/* returns true if $macaddr is a valid MAC address */
214
function is_macaddr($macaddr) {
215
	if (!is_string($macaddr))
216
		return false;
217 98bbf05a Scott Ullrich
218 5b237745 Scott Ullrich
	$maca = explode(":", $macaddr);
219
	if (count($maca) != 6)
220
		return false;
221 98bbf05a Scott Ullrich
222 5b237745 Scott Ullrich
	foreach ($maca as $macel) {
223
		if (($macel === "") || (strlen($macel) > 2))
224
			return false;
225
		if (preg_match("/[^0-9a-f]/i", $macel))
226
			return false;
227
	}
228 98bbf05a Scott Ullrich
229 5b237745 Scott Ullrich
	return true;
230
}
231
232 3caa8aa1 Bill Marquette
/* returns true if $name is a valid name for an alias */
233 9499c2d2 Bill Marquette
/* returns NULL if a reserved word is used */
234 5b237745 Scott Ullrich
function is_validaliasname($name) {
235 beeef1f0 Bill Marquette
	/* Array of reserved words */
236 0c2badde Colin Smith
	$reserved = array("port", "pass");
237
	if (in_array($name, $reserved, true))
238 9499c2d2 Bill Marquette
		return; /* return NULL */
239 beeef1f0 Bill Marquette
240 d87fc50b Seth Mos
	if (!preg_match("/[^a-zA-Z0-9_]/", $name))
241 5b237745 Scott Ullrich
		return true;
242
	else
243
		return false;
244
}
245
246
/* returns true if $port is a valid TCP/UDP port */
247
function is_port($port) {
248
	if (!is_numericint($port))
249
		return false;
250 98bbf05a Scott Ullrich
251 5b237745 Scott Ullrich
	if (($port < 1) || ($port > 65535))
252
		return false;
253
	else
254
		return true;
255
}
256
257 5a1eebc7 Scott Ullrich
/* returns true if $portrange is a valid TCP/UDP portrange ("<port>:<port>") */
258
function is_portrange($portrange) {
259
        $ports = explode(":", $portrange);
260
261
        if(count($ports) == 2 && is_port($ports[0]) && is_port($ports[1]))
262
                return true;
263
        else
264
                return false;
265
}
266
267 b8014f9d Scott Ullrich
/* returns true if $val is a valid shaper bandwidth value */
268
function is_valid_shaperbw($val) {
269 eaa37259 Ermal Luçi
	return (preg_match("/^(\d+(?:\.\d+)?)([MKG]?b|%)$/", $val));
270 b8014f9d Scott Ullrich
}
271
272 c8abe1d4 Ermal Luçi
/* return the configured interfaces list. */
273 3ad5e089 Ermal Luçi
function get_configured_interface_list($only_opt = false, $withdisabled = false) {
274 c8abe1d4 Ermal Luçi
	global $config;
275
276
	$iflist = array();
277
278
	/* if list */
279 42c9d20e Ermal Luçi
        foreach($config['interfaces'] as $if => $ifdetail) {
280 5d0ff141 Seth Mos
		if ($only_opt == true && ($if == "wan" || $if == "lan"))
281 42c9d20e Ermal Luçi
			continue;
282 3ad5e089 Ermal Luçi
		if ($if == "wan" || $if == "lan" || isset($ifdetail['enable']) || 
283
			$withdisabled == true) 
284 c8abe1d4 Ermal Luçi
			$iflist[$if] = $if;
285 42c9d20e Ermal Luçi
	}
286 c8abe1d4 Ermal Luçi
287
	return $iflist;
288
			
289
}
290
291
/* return the configured interfaces list with their description. */
292 3ad5e089 Ermal Luçi
function get_configured_interface_with_descr($only_opt = false, $withdisabled = false) {
293 c8abe1d4 Ermal Luçi
        global $config;
294
295
        $iflist = array();
296
297
        /* if list */
298 42c9d20e Ermal Luçi
        foreach($config['interfaces'] as $if => $ifdetail) {
299 2128f76f Ermal Luçi
               	if ($only_opt == true && ($if == "wan" || $if == "lan"))
300 42c9d20e Ermal Luçi
                        continue;
301 3ad5e089 Ermal Luçi
                if ($if == "wan" || $if == "lan" || isset($ifdetail['enable']) ||
302
			$withdisabled == true) {
303 8ddbd34d Seth Mos
			if($ifdetail['descr'] == "")
304 8e74cb8d Ermal Luçi
				$iflist[$if] = strtoupper($if);
305 3ad5e089 Ermal Luçi
                        else
306
				$iflist[$if] = $ifdetail['descr'];
307 0e218dc1 Ermal Luçi
		}
308 42c9d20e Ermal Luçi
	}
309 c8abe1d4 Ermal Luçi
310
        return $iflist;
311
312
}
313
314
315 36f546e9 Scott Ullrich
/*
316
 *   get_interface_list() - Return a list of all physical interfaces
317
 *   along with MAC and status.
318
 *
319
 *   $mode = "active" - use ifconfig -lu
320
 *           "media"  - use ifconfig to check physical connection
321
 *			status (much slower)
322
 */
323
function get_interface_list($mode = "active", $keyby = "physical", $vfaces = "") {
324 20203646 Colin Smith
        global $config;
325 65bed2d2 Scott Ullrich
	$upints = array();
326 20203646 Colin Smith
        /* get a list of virtual interface types */
327 36f546e9 Scott Ullrich
        if(!$vfaces) {
328 9ce38409 Scott Ullrich
		$vfaces = array (
329
				'bridge',
330
				'ppp',
331
				'sl',
332
				'gif',
333 613571ea Ermal Luçi
				'gre',
334 9ce38409 Scott Ullrich
				'faith',
335
				'lo',
336
				'ng',
337
				'vlan',
338
				'pflog',
339
				'pfsync',
340
				'enc',
341
				'tun',
342 0a140d2e Ermal Luçi
				'carp',
343 178700e6 Ermal Luçi
				'lagg',
344
				'plip'
345 9ce38409 Scott Ullrich
		);
346 36f546e9 Scott Ullrich
	}
347 20203646 Colin Smith
	switch($mode) {
348
	case "active":
349
                $upints = explode(" ", trim(shell_exec("/sbin/ifconfig -lu")));
350
        	break;
351
	case "media":
352
                $intlist = explode(" ", trim(shell_exec("/sbin/ifconfig -l")));
353 767a716e Scott Ullrich
                $ifconfig = "";
354 20203646 Colin Smith
                exec("/sbin/ifconfig -a", $ifconfig);
355
                $regexp = '/(' . implode('|', $intlist) . '):\s/';
356
                $ifstatus = preg_grep('/status:/', $ifconfig);
357 49149b86 Colin Smith
		foreach($ifstatus as $status) {
358 bb3b9159 Colin Smith
			$int = array_shift($intlist);
359
                	if(stristr($status, "active")) $upints[] = $int;
360 49149b86 Colin Smith
		}
361 20203646 Colin Smith
		break;
362
	}
363
        /* build interface list with netstat */
364 767a716e Scott Ullrich
        $linkinfo = "";
365 89d1f0f2 Scott Ullrich
        exec("/usr/bin/netstat -inW -f link | awk '{ print $1, $4 }'", $linkinfo);
366 20203646 Colin Smith
        array_shift($linkinfo);
367 89d1f0f2 Scott Ullrich
	/* build ip address list with netstat */
368 767a716e Scott Ullrich
	$ipinfo = "";
369 89d1f0f2 Scott Ullrich
	exec("/usr/bin/netstat -inW -f inet | awk '{ print $1, $4 }'", $ipinfo);
370
	array_shift($ipinfo);
371
	foreach($linkinfo as $link) {
372
		$friendly = "";
373 20203646 Colin Smith
                $alink = explode(" ", $link);
374
                $ifname = rtrim(trim($alink[0]), '*');
375 36f546e9 Scott Ullrich
                /* trim out all numbers before checking for vfaces */
376
		if (!in_array(array_shift(preg_split('/\d/', $ifname)), $vfaces)) {
377 20203646 Colin Smith
			$toput = array(
378
					"mac" => trim($alink[1]),
379
					"up" => in_array($ifname, $upints)
380
				);
381 89d1f0f2 Scott Ullrich
			foreach($ipinfo as $ip) {
382
				$aip = explode(" ", $ip);
383
				if($aip[0] == $ifname) {
384
					$toput['ipaddr'] = $aip[1];
385
				}
386
			}
387 20203646 Colin Smith
			foreach($config['interfaces'] as $name => $int) {
388
				if($int['if'] == $ifname) $friendly = $name;
389
			}
390
			switch($keyby) {
391
			case "physical":
392 89d1f0f2 Scott Ullrich
				if($friendly != "") {
393
					$toput['friendly'] = $friendly;
394
				}
395 20203646 Colin Smith
				$iflist[$ifname] = $toput;
396 3154d7ed Colin Smith
				break;
397 20203646 Colin Smith
			case "friendly":
398 89d1f0f2 Scott Ullrich
				if($friendly != "") {
399
					$toput['if'] = $ifname;
400
					$iflist[$friendly] = $toput;
401
				}
402 3154d7ed Colin Smith
				break;
403
			}
404 20203646 Colin Smith
                }
405
        }
406
        return $iflist;
407 5b237745 Scott Ullrich
}
408
409
/* wrapper for exec() */
410 12169c92 Seth Mos
function mwexec($command, $mute = false) {
411 5b237745 Scott Ullrich
412
	global $g;
413 f9db3cda Seth Mos
	$oarr = array();
414
	$retval = 0;
415 5b237745 Scott Ullrich
	if ($g['debug']) {
416
		if (!$_SERVER['REMOTE_ADDR'])
417
			echo "mwexec(): $command\n";
418 f9db3cda Seth Mos
		exec("$command 2>&1", $oarr, $retval);
419 5b237745 Scott Ullrich
	} else {
420 f9db3cda Seth Mos
		exec("$command 2>&1", $oarr, $retval);
421
	}
422 12169c92 Seth Mos
	if(($retval <> 0) && ($mute === false)) {
423 f9db3cda Seth Mos
		$output = implode(" ", $oarr);
424 c470830b Scott Ullrich
		//log_error("The command '$command' returned exit code '$retval', the output was '$output' ");
425 5b237745 Scott Ullrich
	}
426 98bbf05a Scott Ullrich
	return $retval;
427 5b237745 Scott Ullrich
}
428
429
/* wrapper for exec() in background */
430
function mwexec_bg($command) {
431
432
	global $g;
433 98bbf05a Scott Ullrich
434 5b237745 Scott Ullrich
	if ($g['debug']) {
435
		if (!$_SERVER['REMOTE_ADDR'])
436
			echo "mwexec(): $command\n";
437
	}
438 98bbf05a Scott Ullrich
439 5b237745 Scott Ullrich
	exec("nohup $command > /dev/null 2>&1 &");
440
}
441
442
/* unlink a file, if it exists */
443
function unlink_if_exists($fn) {
444 336cb718 Scott Ullrich
	$to_do = glob($fn);
445 3b378be5 Scott Ullrich
	if(is_array($to_do)) {
446 336cb718 Scott Ullrich
		foreach($to_do as $filename)
447 9ff926a2 Colin Smith
			@unlink($filename);
448 336cb718 Scott Ullrich
	} else {
449 9ff926a2 Colin Smith
		@unlink($fn);
450 336cb718 Scott Ullrich
	}
451 5b237745 Scott Ullrich
}
452
/* make a global alias table (for faster lookups) */
453 918a884d Bill Marquette
function alias_make_table($config) {
454 98bbf05a Scott Ullrich
455 918a884d Bill Marquette
	global $aliastable;
456 98bbf05a Scott Ullrich
457 5b237745 Scott Ullrich
	$aliastable = array();
458 98bbf05a Scott Ullrich
459 5b237745 Scott Ullrich
	if (is_array($config['aliases']['alias'])) {
460
		foreach ($config['aliases']['alias'] as $alias) {
461
			if ($alias['name'])
462
				$aliastable[$alias['name']] = $alias['address'];
463
		}
464
	}
465
}
466
/* check if an alias exists */
467
function is_alias($name) {
468 98bbf05a Scott Ullrich
469 5b237745 Scott Ullrich
	global $aliastable;
470 98bbf05a Scott Ullrich
471 5b237745 Scott Ullrich
	return isset($aliastable[$name]);
472 b8014f9d Scott Ullrich
}
473 27ff8a3c Scott Ullrich
474
function alias_expand_value($name) {
475
476
	global $aliastable, $config;
477 c2472fe9 Scott Ullrich
	$newaddress = "";
478
	$firstentry = true;
479 800e9138 Scott Ullrich
	if($config['aliases']['alias'])
480
		foreach($config['aliases']['alias'] as $alias) {
481 c2472fe9 Scott Ullrich
			if($alias['name'] == $name) {
482
				if($alias['type'] == "openvpn") {
483
					$vpn_address_split = split(" ", $alias['address']);
484
					foreach($vpn_address_split as $vpnsplit) {
485
						foreach($config['openvpn']['user'] as $openvpn) {
486
							if($openvpn['name'] == $vpnsplit) {
487
								if($firstentry == false) 
488
									$newaddress .= " ";
489
								$newaddress .= $openvpn['ip'];
490
								$firstentry = false;
491
							}
492
						}
493
					}
494
				} else {
495
					$newaddress = $alias['address'];
496
				}
497
			}
498 800e9138 Scott Ullrich
		}
499 c2472fe9 Scott Ullrich
		return $newaddress;
500 5b237745 Scott Ullrich
}
501
502
/* expand a host or network alias, if necessary */
503
function alias_expand($name) {
504 98bbf05a Scott Ullrich
505 5b237745 Scott Ullrich
	global $aliastable;
506 98bbf05a Scott Ullrich
507 5b237745 Scott Ullrich
	if (isset($aliastable[$name]))
508 4335dc87 Bill Marquette
		return "\${$name}";
509 5b237745 Scott Ullrich
	else if (is_ipaddr($name) || is_subnet($name))
510 57989da5 Scott Ullrich
		return "{$name}";
511 5b237745 Scott Ullrich
	else
512
		return null;
513
}
514
515
/* expand a host alias, if necessary */
516
function alias_expand_host($name) {
517
	global $aliastable;
518 98bbf05a Scott Ullrich
519 9b00dc26 Bill Marquette
	if (isset($aliastable[$name])) {
520
		$ip_arr = explode(" ", $aliastable[$name]);
521
		foreach($ip_arr as $ip) {
522
			if (!is_ipaddr($ip))
523
				return null;
524
		}
525 5b237745 Scott Ullrich
		return $aliastable[$name];
526 9b00dc26 Bill Marquette
	} else if (is_ipaddr($name))
527 5b237745 Scott Ullrich
		return $name;
528
	else
529
		return null;
530
}
531
532
/* expand a network alias, if necessary */
533
function alias_expand_net($name) {
534 98bbf05a Scott Ullrich
535 5b237745 Scott Ullrich
	global $aliastable;
536 98bbf05a Scott Ullrich
537 5b237745 Scott Ullrich
	if (isset($aliastable[$name]) && is_subnet($aliastable[$name]))
538
		return $aliastable[$name];
539
	else if (is_subnet($name))
540
		return $name;
541
	else
542
		return null;
543
}
544
545
/* find out whether two subnets overlap */
546
function check_subnets_overlap($subnet1, $bits1, $subnet2, $bits2) {
547
548
	if (!is_numeric($bits1))
549
		$bits1 = 32;
550
	if (!is_numeric($bits2))
551
		$bits2 = 32;
552
553
	if ($bits1 < $bits2)
554
		$relbits = $bits1;
555
	else
556
		$relbits = $bits2;
557 98bbf05a Scott Ullrich
558 5b237745 Scott Ullrich
	$sn1 = gen_subnet_mask_long($relbits) & ip2long($subnet1);
559
	$sn2 = gen_subnet_mask_long($relbits) & ip2long($subnet2);
560 98bbf05a Scott Ullrich
561 5b237745 Scott Ullrich
	if ($sn1 == $sn2)
562
		return true;
563
	else
564
		return false;
565
}
566
567
/* compare two IP addresses */
568
function ipcmp($a, $b) {
569
	if (ip2long($a) < ip2long($b))
570
		return -1;
571
	else if (ip2long($a) > ip2long($b))
572
		return 1;
573
	else
574
		return 0;
575
}
576
577
/* return true if $addr is in $subnet, false if not */
578
function ip_in_subnet($addr,$subnet) {
579
	list($ip, $mask) = explode('/', $subnet);
580
	$mask = 0xffffffff << (32 - $mask);
581
	return ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
582
}
583
584
/* verify (and remove) the digital signature on a file - returns 0 if OK */
585
function verify_digital_signature($fname) {
586
587
	global $g;
588
589 f024f52d Scott Ullrich
	return mwexec("/usr/local/sbin/gzsig verify {$g['etc_path']}/pubkey.pem < " . escapeshellarg($fname));
590
591 5b237745 Scott Ullrich
}
592
593
/* obtain MAC address given an IP address by looking at the ARP table */
594
function arp_get_mac_by_ip($ip) {
595 08443c7a Chris Dionissopoulos
	mwexec("/sbin/ping -c 1 -t 1 {$ip}");
596 767a716e Scott Ullrich
	$arpoutput = "";
597 5b237745 Scott Ullrich
	exec("/usr/sbin/arp -n {$ip}", $arpoutput);
598 98bbf05a Scott Ullrich
599 5b237745 Scott Ullrich
	if ($arpoutput[0]) {
600
		$arpi = explode(" ", $arpoutput[0]);
601
		$macaddr = $arpi[3];
602
		if (is_macaddr($macaddr))
603
			return $macaddr;
604
		else
605
			return false;
606
	}
607 98bbf05a Scott Ullrich
608 5b237745 Scott Ullrich
	return false;
609
}
610
611 98bbf05a Scott Ullrich
/* return a fieldname that is safe for xml usage */
612
function xml_safe_fieldname($fieldname) {
613 ddce8ef2 Colin Smith
	$replace = array('/', '-', ' ', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
614 9ef924eb Colin Smith
			 '_', '+', '=', '{', '}', '[', ']', '|', '/', '<', '>', '?',
615 ddce8ef2 Colin Smith
			 ':', ',', '.', '\'', '\\'
616
		);
617
	return strtolower(str_replace($replace, "", $fieldname));
618 98bbf05a Scott Ullrich
}
619
620 4129df39 Scott Ullrich
function mac_format($clientmac) {
621
    $mac =explode(":", $clientmac);
622
623
    global $config;
624
625
    $mac_format = $config['captiveportal']['radmac_format'] ? $config['captiveportal']['radmac_format'] : false;
626
627
    switch($mac_format) {
628
629
        case 'singledash':
630
        return "$mac[0]$mac[1]$mac[2]-$mac[3]$mac[4]$mac[5]";
631
632
        case 'ietf':
633
        return "$mac[0]-$mac[1]-$mac[2]-$mac[3]-$mac[4]-$mac[5]";
634
635
        case 'cisco':
636
        return "$mac[0]$mac[1].$mac[2]$mac[3].$mac[4]$mac[5]";
637
638
        case 'unformatted':
639
        return "$mac[0]$mac[1]$mac[2]$mac[3]$mac[4]$mac[5]";
640
641
        default:
642
        return $clientmac;
643
    }
644
}
645
646 979cd6db Scott Ullrich
function resolve_retry($hostname, $retries = 5) {
647
648
       if (is_ipaddr($hostname))
649
               return $hostname;
650
651
       for ($i = 0; $i < $retries; $i++) {
652
               $ip = gethostbyname($hostname);
653
654
               if ($ip && $ip != $hostname) {
655
                       /* success */
656
                       return $ip;
657
               }
658
659
               sleep(1);
660
       }
661
662
       return false;
663
}
664
665 44bfd1fa Scott Ullrich
function format_bytes($bytes) {
666
	if ($bytes >= 1073741824) {
667
		return sprintf("%.2f GB", $bytes/1073741824);
668
	} else if ($bytes >= 1048576) {
669
		return sprintf("%.2f MB", $bytes/1048576);
670
	} else if ($bytes >= 1024) {
671
		return sprintf("%.0f KB", $bytes/1024);
672
	} else {
673
		return sprintf("%d bytes", $bytes);
674
	}
675
}
676
677 c470830b Scott Ullrich
?>