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