[SPIP] +2.1.12
[velocampus/web/www.git] / www / ecrire / inc / nfslock.php
1 <?php
2 /*
3 *
4 *
5 * function: nfslock
6 * original author: Chuck Cranor <chuck@maria.wustl.edu>
7 * rewritten by: Alexis Rosen <alexis@panix.com>
8 * rewritten by: Cedric Morin <cedric@yterium.com> for php&SPIP
9 *
10 * (Excerpts from Chuck's notes:
11 * this becomes complex, due to our dear friend, the NFS mounted mail spool.
12 * the netbsd code didn't do this properly, as far as I could tell.
13 *
14 * - you can't trust exclusive creating opens over NFS, the protocol
15 * just doesn't support it. so to do a lock you have to create
16 * a tmp file and then try and hard link it to your lock file.
17 * - to detect a stale lock file you have to see how old it is, but
18 * you can't use time(0) because that is the time on the local system
19 * and the file gets the times of the NFS server. when is a lock
20 * file stale? people seem to like 120 or 300 seconds.)
21 *
22 * NB: It is _critical_ that nfslock()ed files be unlocked by nfsunlock().
23 * Simply unlinking the lock file is a good way to trash someone else's lock
24 * file. All it takes is for the process doing the unlink to get hung for
25 * a few minutes when it doesn't expect it. Meanwhile, its lock expires and
26 * a second process forces the lock and creates its own. Then the first
27 * process comes along and kills the second process' lock while it's still
28 * valid.
29 *
30 * Security considerations:
31 * If we're root, be very careful to see that the temp file we opened is
32 * what we think it is. The problem is that we could lose a race with
33 * someone who takes our tmp file and replaces it with, say, a hard
34 * link to /etc/passwd. Then, if the first lock attempt fails, we'll
35 * write a char to the file (see 4. below); this would truncate the
36 * passwd file. So we make sure that the link count is 1. We don't really
37 * care about any other screwing around since we don't write anything
38 * sensitive to the lock file, nor do we change its owner or mode. If
39 * someone beats us on a race and replaces our temp file with anything
40 * else, it's no big deal- the file may get truncated, but there's no
41 * possible security breach. ...Actually the possibility of the race
42 * ever happening, given the random name of the file, is virtually nil.
43 *
44 * args: path = path to directory of lock file (/net/u/1/a/alexis/.mailspool)
45 * namelock = file name of lock file (alexis.lock)
46 * max_age = age of lockfile, in seconds, after which the lock is stale.
47 * stale locks are always broken. Defaults to DEFAULT_LOCKTIME
48 * if zero. Panix mail locks go stale at 300 seconds, the default.
49 * notify = 1 if we should tell stdout that we're sleeping on a lock
50 *
51 * Returns the time that the lock was created on the other system. This is
52 * important for nfsunlock(). If the lock already exists, returns NFSL_LOCKED.
53 * If there is some other failure, return NFSL_SYSF. If NFSL_LOCKED is
54 * returned, errno is also set to EEXIST. If we're root and the link count
55 * on the tmp file is wrong, return NFSL_SECV.
56 *
57 * Mods of 7/13/95: Change a bit of code to re-stat the lockfile after
58 * closing it. This is to work around a bug in SunOS that appears to to affect
59 * some SunOS 4.1.3 machines (but not all). The bug is that close() updates
60 * the stat st_ctime field for that file. So use lstat on fullpath instead
61 * of fstat on tmpfd. This alteration applies to both nfslock and nfslock1.
62 *
63 * Mod of 5/4/95: Change printf's to fprintf(stderr... in nfslock and nfslock1.
64 *
65 * Mods of 4/29/95: Fix freeing memory before use if a stat fails. Remove
66 * code that forbids running as root; instead, if root, check link count on
67 * tmp file after opening it.
68 *
69 * Mods of 4/27/95: Return the create time instead of the lockfile's fd, which
70 * is useless. Added new routines nfsunlock(), nfslock_test(), nfslock_renew().
71 *
72 * Mods of 1/8/95: Eliminate some security checks since this code never
73 * runs as root. In particular, we completely eliminate the safeopen
74 * routine. But add one check: if we _are_ root, fail immediately.
75 *
76 * Change arguments: take a path and a filename. Don't assume a global or
77 * macro pointing to a mailspool.
78 *
79 * Add notify argument; if 1, tell user when we're waiting for a lock.
80 *
81 * Add max_age argument and DEFAULT_LOCKTIME.
82 *
83 * Change comments drastically.
84 *
85 */
86
87 if (!defined('_ECRIRE_INC_VERSION')) return;
88
89 include_spip('inc/acces');
90 define('_DEFAULT_LOCKTIME',60);
91 define('_NAME_LOCK','spip_nfs_lock');
92
93 // http://doc.spip.org/@spip_nfslock
94 function spip_nfslock($fichier,$max_age=0) {
95 $tries = 0;
96
97 if (!$max_age) $max_age = _DEFAULT_LOCKTIME;
98 $lock_file = _DIR_TMP . _NAME_LOCK . "-" . substr(md5($fichier),0,8);
99
100
101 /*
102 * 1. create a tmp file with a psuedo random file name. we also make
103 * tpath which is a buffer to store the full pathname of the tmp file.
104 */
105
106 $id = creer_uniqid();
107 $tpath = _DIR_TMP."slock.$id";
108 $tmpfd = @fopen($tpath, 'w'); // hum, le 'x' necessite php4,3,2 ...
109 if (!$tmpfd) { /* open failed */
110 @fclose($tmpfd);
111 spip_unlink($tpath);
112 return false; //NFSL_SYSF
113 }
114
115 /*
116 * 2. make fullpath, a buffer for the full pathname of the lock file.
117 * then start looping trying to lock it
118 */
119
120 while ($tries < 10) {
121 /*
122 * 3. link tmp file to lock file. if it goes, we win and we clean
123 * up and return the st_ctime of the lock file.
124 */
125
126 if (link($tpath, $lock_file) == 1) {
127 spip_unlink($tpath); /* got it! */
128 @fclose($tmpfd);
129 if (($our_tmp = lstat($lock_file))==false) { /* stat failed... shouldn't happen */
130 spip_unlink($lock_file);
131 return false; // (NFSL_SYSF);
132 }
133 return($our_tmp['ctime']);
134 }
135
136 /*
137 * 4. the lock failed. check for a stale lock file, being mindful
138 * of NFS and the fact the time is set from the NFS server. we
139 * do a write on the tmp file to update its time to the server's
140 * idea of "now."
141 */
142
143 $old_stat = lstat($lock_file);
144 if (@fputs($tmpfd, "zz", 2)!=2 || !$our_tmp=fstat($tmpfd))
145 break; /* something bogus is going on */
146
147
148 if ($old_stat!=false && (($old_stat['ctime'] + $max_age) < $our_tmp['ctime'])) {
149 spip_unlink($lock_file); /* break the stale lock */
150 $tries++;
151 /* It is CRITICAL that we sleep after breaking
152 * the lock. Otherwise, we could race with
153 * another process and unlink it's newly-
154 * created file.
155 */
156 sleep(1+rand(0,4));
157 continue;
158 }
159
160 /*
161 * 5. try again
162 */
163
164 $tries++;
165 sleep(1+rand(0,4));
166 }
167
168 /*
169 * 6. give up, failure.
170 */
171
172 spip_unlink($tpath);
173 @fclose($tmpfd);
174 return false; //(NFSL_LOCKED);
175 }
176
177 /*
178 * function: nfsunlock
179 * author: Alexis Rosen <alexis@panix.com>
180 *
181 * Unlock an nfslock()ed file.
182 *
183 * This can get tricky because the lock may have expired (perhaps even
184 * during a process that should be "atomic"). We have to make sure we don't
185 * unlock some other process' lock, and return a panic code if we think our
186 * lock file has been broken illegally. What's done in reaction to that panic
187 * (of anything) is up to the caller. See the comments on nfslock()!
188 *
189 * args: path = path to directory of lock file (/net/u/1/a/alexis/.mailspool)
190 * namelock = file name of lock file (alexis.lock)
191 * max_age = age of lockfile, in seconds, after which the lock is stale.
192 * stale locks are always broken. Defaults to DEFAULT_LOCKTIME
193 * if zero. Panix mail locks go stale at 300 seconds, the default.
194 * birth = time the lock was created (as returned by nfslock()).
195 *
196 * Returns NFSL_OK if successful, NFSL_LOST if the lock has been lost
197 * legitimately (because more than max_age has passed since the lock was
198 * created), and NFSL_STOLEN if it's been tampered with illegally (i.e.
199 * while this program is within the expiry period). Returns NFSL_SYSF if
200 * another system failure prevents it from even trying to unlock the file.
201 *
202 * Note that for many programs, a return code of NFSL_LOST or NFSL_STOLEN is
203 * equally disastrous; a NFSL_STOLEN means that some other program may have
204 * trashed your file, but a NFSL_LOST may mean that _you_ have trashed someone
205 * else's file (if in fact you wrote the file that you locked after you lost
206 * the lock) or that you read inconsistent information.
207 *
208 * In practice, a return code of NFSL_LOST or NFSL_STOLEN will virtually never
209 * happen unless someone is violating the locking protocol.
210 *
211 */
212
213 // http://doc.spip.org/@spip_nfsunlock
214 function spip_nfsunlock($fichier, $birth, $max_age=0, $test = false) {
215 $id = creer_uniqid();
216 if (!$max_age) $max_age = _DEFAULT_LOCKTIME;
217
218 /*
219 * 1. Build a temp file and stat that to get an idea of what the server
220 * thinks the current time is (our_tmp.st_ctime)..
221 */
222
223 $tpath = _DIR_TMP."stime.$id";
224 $tmpfd = @fopen($tpath,'w');
225 if ((!$tmpfd)
226 OR (@fputs($tmpfd, "zz", 2) != 2)
227 OR !($our_tmp = fstat($tmpfd))) {
228 /* The open failed, or we can't write the file, or we can't stat it */
229 @fclose($tmpfd);
230 spip_unlink($tpath);
231 return false; //(NFSL_SYSF);
232 }
233
234 @fclose($tmpfd); /* We don't need this once we have our_tmp.st_ctime. */
235 spip_unlink($tpath);
236
237 /*
238 * 2. make fullpath, a buffer for the full pathname of the lock file
239 */
240
241 $lock_file = _DIR_TMP . _NAME_LOCK . "-" . substr(md5($fichier),0,8);
242
243 /*
244 * 3. If the ctime hasn't been modified, unlink the file and return. If the
245 * lock has expired, sleep the usual random interval before returning.
246 * If we didn't sleep, there could be a race if the caller immediately
247 * tries to relock the file.
248 */
249
250 if ( ($old_stat=@lstat($lock_file)) /* stat succeeds so file is there */
251 && ($old_stat['ctime'] == $birth)) { /* hasn't been modified since birth */
252 if (!$test)
253 spip_unlink($lock_file); /* so the lock is ours to remove */
254 if ($our_tmp['ctime'] >= $birth + $max_age){ /* the lock has expired */
255 if (!$test) return false; //(NFSL_LOST);
256 sleep(1+(random(0,4))); /* so sleep a bit */
257 }
258 return true;//(NFSL_OK); /* success */
259 }
260
261 /*
262 * 4. Either ctime has been modified, or the entire lock file is missing.
263 * If the lock should still be ours, based on the ctime of the temp
264 * file, return with NFSL_STOLEN. If not, then our lock is expired and
265 * someone else has grabbed the file, so return NFSL_LOST.
266 */
267
268 if ($our_tmp['ctime'] < $birth + $max_age) /* lock was stolen */
269 return false; //(NFSL_STOLEN);
270
271 return false; //(NFSL_LOST); /* The lock must have expired first. */
272 }
273
274
275 /*
276 * function: nfslock_test
277 * author: Alexis Rosen <alexis@panix.com>
278 *
279 * Test a lock to see if it's still valid.
280 *
281 * See the comments in nfsunlock() about lost and stolen locks.
282 *
283 * Args, return codes, and behavior are identical to nfsunlock except
284 * that nfslock_test doesn't remove the lock. NFSL_OK means the lock is
285 * good, NFLS_LOST and NFSL_STOLEN means it's bad, and NFSL_SYSF means
286 * we couldn't tell due to system failure.
287 *
288 * The source for this routine is almost identical to nfsunlock(), but it's
289 * coded separately to make things as clear as possible.
290 */
291
292 // http://doc.spip.org/@spip_nfslock_test
293 function spip_nfslock_test($fichier, $birth, $max_age=0) {
294 return spip_nfsunlock($fichier, $birth, $max_age, true);
295 }
296
297 ?>