forked from FreePBX/firewall
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLock.class.php
More file actions
94 lines (85 loc) · 2.28 KB
/
Copy pathLock.class.php
File metadata and controls
94 lines (85 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
// vim: :set filetype=php tabstop=4 shiftwidth=4 autoindent smartindent:
//
namespace FreePBX\modules\Firewall;
class Lock {
private static $locks;
public static function getLockDir() {
// Change this to be smarter in 15. For the moment, stick with only using /tmp
return "/tmp";
// The following code is unused.
/*
static $dir = false;
if (!$dir) {
// We want to use, in order of preference, /var/run/locks, /run/locks, and
// fall back to /tmp/locks.
//
// However, if this is an upgrade, /tmp/locks will already exist, so just
// keep using that until the machine is rebooted.
//
if (is_dir("/tmp/locks")) {
$dir = "/tmp";
return $dir;
}
$order = array("/dev/shm", "/var/run", "/run", "/tmp");
foreach ($order as $check) {
if (is_dir($check)) {
$dir = $check;
break;
}
}
}
// If /tmp doesn't exist, we have worse problems than firewall breaking.
return $dir;
*/
}
public static function canLock($lockname = false) {
if (!$lockname) {
throw new \Exception("No lock given");
}
// So, we see if we CAN lock a name, and if we can, lock it.
$lockdir = self::getLockDir();
if (!is_dir("$lockdir/locks")) {
@unlink("$lockdir/locks");
mkdir("$lockdir/locks");
@chmod("$lockdir/locks", 0666);
if (!is_dir("$lockdir/locks")) {
throw new \Exception("Can't create $lockdir/locks directory");
}
}
$lf = "$lockdir/locks/lock-$lockname";
$lockfh = fopen($lf, "c"); // Create it if it doesn't exist
@chmod($lf, 0666);
if (!flock($lockfh, LOCK_EX|LOCK_NB)) {
// Unable to lock the file.
return false;
}
// Yay, we locked it!
if (!is_array(self::$locks)) {
self::$locks = array($lockname => $lockfh);
} else {
self::$locks[$lockname] = $lockfh;
}
return true;
}
public static function unLock($lockname = false) {
if (!$lockname) {
throw new \Exception("No lock given");
}
if (!is_array(self::$locks)) {
print "Tried to unlock before anything was locked\n";
return false;
} else {
if (!isset(self::$locks[$lockname])) {
print "Tried to unlock something that wasn't locked\n";
return false;
}
$lockfh = self::$locks[$lockname];
flock($lockfh, LOCK_UN);
fclose($lockfh);
unset(self::$locks[$lockname]);
unset($lockfh);
}
return true;
}
}