PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/ecrire/inc/nfslock.php

https://github.com/denisbz/SPIP-1
PHP | 297 lines | 76 code | 34 blank | 187 comment | 21 complexity | 850de3f557e9f1c4366fcc1ad637f87c MD5 | raw file
  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. if (!defined('_ECRIRE_INC_VERSION')) return;
  87. include_spip('inc/acces');
  88. define('_DEFAULT_LOCKTIME',60);
  89. define('_NAME_LOCK','spip_nfs_lock');
  90. // http://doc.spip.org/@spip_nfslock
  91. function spip_nfslock($fichier,$max_age=0) {
  92. $tries = 0;
  93. if (!$max_age) $max_age = _DEFAULT_LOCKTIME;
  94. $lock_file = _DIR_TMP . _NAME_LOCK . "-" . substr(md5($fichier),0,8);
  95. /*
  96. * 1. create a tmp file with a psuedo random file name. we also make
  97. * tpath which is a buffer to store the full pathname of the tmp file.
  98. */
  99. $id = creer_uniqid();
  100. $tpath = _DIR_TMP."slock.$id";
  101. $tmpfd = @fopen($tpath, 'w'); // hum, le 'x' necessite php4,3,2 ...
  102. if (!$tmpfd) { /* open failed */
  103. @fclose($tmpfd);
  104. spip_unlink($tpath);
  105. return false; //NFSL_SYSF
  106. }
  107. /*
  108. * 2. make fullpath, a buffer for the full pathname of the lock file.
  109. * then start looping trying to lock it
  110. */
  111. while ($tries < 10) {
  112. /*
  113. * 3. link tmp file to lock file. if it goes, we win and we clean
  114. * up and return the st_ctime of the lock file.
  115. */
  116. if (link($tpath, $lock_file) == 1) {
  117. spip_unlink($tpath); /* got it! */
  118. @fclose($tmpfd);
  119. if (($our_tmp = lstat($lock_file))==false) { /* stat failed... shouldn't happen */
  120. spip_unlink($lock_file);
  121. return false; // (NFSL_SYSF);
  122. }
  123. return($our_tmp['ctime']);
  124. }
  125. /*
  126. * 4. the lock failed. check for a stale lock file, being mindful
  127. * of NFS and the fact the time is set from the NFS server. we
  128. * do a write on the tmp file to update its time to the server's
  129. * idea of "now."
  130. */
  131. $old_stat = lstat($lock_file);
  132. if (@fputs($tmpfd, "zz", 2)!=2 || !$our_tmp=fstat($tmpfd))
  133. break; /* something bogus is going on */
  134. if ($old_stat!=false && (($old_stat['ctime'] + $max_age) < $our_tmp['ctime'])) {
  135. spip_unlink($lock_file); /* break the stale lock */
  136. $tries++;
  137. /* It is CRITICAL that we sleep after breaking
  138. * the lock. Otherwise, we could race with
  139. * another process and unlink it's newly-
  140. * created file.
  141. */
  142. sleep(1+rand(0,4));
  143. continue;
  144. }
  145. /*
  146. * 5. try again
  147. */
  148. $tries++;
  149. sleep(1+rand(0,4));
  150. }
  151. /*
  152. * 6. give up, failure.
  153. */
  154. spip_unlink($tpath);
  155. @fclose($tmpfd);
  156. return false; //(NFSL_LOCKED);
  157. }
  158. /*
  159. * function: nfsunlock
  160. * author: Alexis Rosen <alexis@panix.com>
  161. *
  162. * Unlock an nfslock()ed file.
  163. *
  164. * This can get tricky because the lock may have expired (perhaps even
  165. * during a process that should be "atomic"). We have to make sure we don't
  166. * unlock some other process' lock, and return a panic code if we think our
  167. * lock file has been broken illegally. What's done in reaction to that panic
  168. * (of anything) is up to the caller. See the comments on nfslock()!
  169. *
  170. * args: path = path to directory of lock file (/net/u/1/a/alexis/.mailspool)
  171. * namelock = file name of lock file (alexis.lock)
  172. * max_age = age of lockfile, in seconds, after which the lock is stale.
  173. * stale locks are always broken. Defaults to DEFAULT_LOCKTIME
  174. * if zero. Panix mail locks go stale at 300 seconds, the default.
  175. * birth = time the lock was created (as returned by nfslock()).
  176. *
  177. * Returns NFSL_OK if successful, NFSL_LOST if the lock has been lost
  178. * legitimately (because more than max_age has passed since the lock was
  179. * created), and NFSL_STOLEN if it's been tampered with illegally (i.e.
  180. * while this program is within the expiry period). Returns NFSL_SYSF if
  181. * another system failure prevents it from even trying to unlock the file.
  182. *
  183. * Note that for many programs, a return code of NFSL_LOST or NFSL_STOLEN is
  184. * equally disastrous; a NFSL_STOLEN means that some other program may have
  185. * trashed your file, but a NFSL_LOST may mean that _you_ have trashed someone
  186. * else's file (if in fact you wrote the file that you locked after you lost
  187. * the lock) or that you read inconsistent information.
  188. *
  189. * In practice, a return code of NFSL_LOST or NFSL_STOLEN will virtually never
  190. * happen unless someone is violating the locking protocol.
  191. *
  192. */
  193. // http://doc.spip.org/@spip_nfsunlock
  194. function spip_nfsunlock($fichier, $birth, $max_age=0, $test = false) {
  195. $id = creer_uniqid();
  196. if (!$max_age) $max_age = _DEFAULT_LOCKTIME;
  197. /*
  198. * 1. Build a temp file and stat that to get an idea of what the server
  199. * thinks the current time is (our_tmp.st_ctime)..
  200. */
  201. $tpath = _DIR_TMP."stime.$id";
  202. $tmpfd = @fopen($tpath,'w');
  203. if ((!$tmpfd)
  204. OR (@fputs($tmpfd, "zz", 2) != 2)
  205. OR !($our_tmp = fstat($tmpfd))) {
  206. /* The open failed, or we can't write the file, or we can't stat it */
  207. @fclose($tmpfd);
  208. spip_unlink($tpath);
  209. return false; //(NFSL_SYSF);
  210. }
  211. @fclose($tmpfd); /* We don't need this once we have our_tmp.st_ctime. */
  212. spip_unlink($tpath);
  213. /*
  214. * 2. make fullpath, a buffer for the full pathname of the lock file
  215. */
  216. $lock_file = _DIR_TMP . _NAME_LOCK . "-" . substr(md5($fichier),0,8);
  217. /*
  218. * 3. If the ctime hasn't been modified, unlink the file and return. If the
  219. * lock has expired, sleep the usual random interval before returning.
  220. * If we didn't sleep, there could be a race if the caller immediately
  221. * tries to relock the file.
  222. */
  223. if ( ($old_stat=@lstat($lock_file)) /* stat succeeds so file is there */
  224. && ($old_stat['ctime'] == $birth)) { /* hasn't been modified since birth */
  225. if (!$test)
  226. spip_unlink($lock_file); /* so the lock is ours to remove */
  227. if ($our_tmp['ctime'] >= $birth + $max_age){ /* the lock has expired */
  228. if (!$test) return false; //(NFSL_LOST);
  229. sleep(1+(random(0,4))); /* so sleep a bit */
  230. }
  231. return true;//(NFSL_OK); /* success */
  232. }
  233. /*
  234. * 4. Either ctime has been modified, or the entire lock file is missing.
  235. * If the lock should still be ours, based on the ctime of the temp
  236. * file, return with NFSL_STOLEN. If not, then our lock is expired and
  237. * someone else has grabbed the file, so return NFSL_LOST.
  238. */
  239. if ($our_tmp['ctime'] < $birth + $max_age) /* lock was stolen */
  240. return false; //(NFSL_STOLEN);
  241. return false; //(NFSL_LOST); /* The lock must have expired first. */
  242. }
  243. /*
  244. * function: nfslock_test
  245. * author: Alexis Rosen <alexis@panix.com>
  246. *
  247. * Test a lock to see if it's still valid.
  248. *
  249. * See the comments in nfsunlock() about lost and stolen locks.
  250. *
  251. * Args, return codes, and behavior are identical to nfsunlock except
  252. * that nfslock_test doesn't remove the lock. NFSL_OK means the lock is
  253. * good, NFLS_LOST and NFSL_STOLEN means it's bad, and NFSL_SYSF means
  254. * we couldn't tell due to system failure.
  255. *
  256. * The source for this routine is almost identical to nfsunlock(), but it's
  257. * coded separately to make things as clear as possible.
  258. */
  259. // http://doc.spip.org/@spip_nfslock_test
  260. function spip_nfslock_test($fichier, $birth, $max_age=0) {
  261. return spip_nfsunlock($fichier, $birth, $max_age, true);
  262. }
  263. ?>