PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/ecrire/inc/nfslock.php

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