file_lock.c 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /* Copyright 2016, Google Inc.
  2. * All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are
  6. * met:
  7. *
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above
  11. * copyright notice, this list of conditions and the following
  12. * disclaimer in the documentation and/or other materials provided
  13. * with the distribution.
  14. * * Neither the name of Google Inc. nor the names of its
  15. * contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *
  30. * Alternatively, this software may be distributed under the terms of the
  31. * GNU General Public License ("GPL") version 2 as published by the Free
  32. * Software Foundation.
  33. *
  34. * file_lock.c: Implementation for a binary semaphore using a file lock.
  35. *
  36. * Warning: This relies on flock() which is known to be broken on NFS.
  37. *
  38. * The file will remain persistent once the lock has been used. Unfortunately,
  39. * unlinking the file can introduce a race condition so we leave the file
  40. * in place.
  41. *
  42. * The current process's PID will be written to the file for debug purposes.
  43. */
  44. #include <errno.h>
  45. #include <fcntl.h>
  46. #include <inttypes.h>
  47. #include <limits.h>
  48. #include <stdio.h>
  49. #include <stdlib.h>
  50. #include <string.h>
  51. #include <time.h>
  52. #include <unistd.h>
  53. #include <sys/file.h>
  54. #include <sys/types.h>
  55. #include <sys/stat.h>
  56. #include "android.h"
  57. #include "flash.h"
  58. #include "ipc_lock.h"
  59. #include "locks.h"
  60. #define SLEEP_INTERVAL_MS 50
  61. static void msecs_to_timespec(int msecs, struct timespec *tmspec)
  62. {
  63. tmspec->tv_sec = msecs / 1000;
  64. tmspec->tv_nsec = (msecs % 1000) * 1000 * 1000;
  65. }
  66. static int lock_is_held(struct ipc_lock *lock)
  67. {
  68. return lock->is_held;
  69. }
  70. static int test_dir(const char *path)
  71. {
  72. struct stat s;
  73. if (lstat(path, &s) < 0) {
  74. msg_gerr("Cannot stat %s.\n", path);
  75. return -1;
  76. }
  77. if (!S_ISDIR(s.st_mode)) {
  78. msg_gerr("%s is not a directory.\n", path);
  79. return -1;
  80. }
  81. return 0;
  82. }
  83. static int file_lock_open_or_create(struct ipc_lock *lock)
  84. {
  85. char path[PATH_MAX];
  86. if (in_android()) {
  87. char *tmpdir;
  88. tmpdir = android_tmpdir_path();
  89. if (!tmpdir)
  90. return -1;
  91. if (snprintf(path, sizeof(path), "%s/%s",
  92. tmpdir, lock->filename) < 0) {
  93. return -1;
  94. }
  95. } else {
  96. const char *dir = SYSTEM_LOCKFILE_DIR;
  97. const char fallback[] = "/tmp";
  98. if (test_dir(dir)) {
  99. dir = fallback;
  100. msg_gerr("Trying fallback directory: %s\n", dir);
  101. if (test_dir(dir))
  102. return -1;
  103. }
  104. if (snprintf(path, sizeof(path),
  105. "%s/%s", dir, lock->filename) < 0)
  106. return -1;
  107. }
  108. lock->fd = open(path, O_RDWR | O_CREAT, 0600);
  109. if (lock->fd < 0) {
  110. msg_gerr("Cannot open lockfile %s", path);
  111. return -1;
  112. }
  113. msg_gdbg("Opened file lock \"%s\"\n", path);
  114. return 0;
  115. }
  116. static int file_lock_get(struct ipc_lock *lock, int timeout_msecs)
  117. {
  118. int msecs_remaining = timeout_msecs;
  119. struct timespec sleep_interval, rem;
  120. int ret = -1;
  121. if (timeout_msecs == 0)
  122. return flock(lock->fd, LOCK_EX | LOCK_NB);
  123. msecs_to_timespec(SLEEP_INTERVAL_MS, &sleep_interval);
  124. while ((ret = flock(lock->fd, LOCK_EX | LOCK_NB)) != 0) {
  125. if (errno != EWOULDBLOCK) {
  126. msg_gerr("Error obtaining lock");
  127. return -1;
  128. }
  129. if (msecs_remaining < SLEEP_INTERVAL_MS)
  130. msecs_to_timespec(msecs_remaining, &sleep_interval);
  131. while (nanosleep(&sleep_interval, &rem) != 0) {
  132. if (errno == EINTR) {
  133. sleep_interval = rem;
  134. continue;
  135. } else {
  136. msg_gerr("nanosleep() failed");
  137. return ret;
  138. }
  139. }
  140. if (timeout_msecs < 0)
  141. continue;
  142. msecs_remaining -= SLEEP_INTERVAL_MS;
  143. if (msecs_remaining < 0)
  144. break;
  145. }
  146. if (ret != 0) {
  147. msg_gerr("Timed out waiting for file lock.\n");
  148. return -1;
  149. }
  150. return 0;
  151. }
  152. static int file_lock_write_pid(struct ipc_lock *lock)
  153. {
  154. ssize_t len;
  155. /* PIDs are usually 5 digits, but we'll reserve enough room for
  156. a value of 2^32 (10 digits) out of paranoia. */
  157. char pid_str[11];
  158. if (ftruncate(lock->fd, 0) < 0) {
  159. msg_gerr("Cannot truncate lockfile");
  160. return -1;
  161. }
  162. snprintf(pid_str, sizeof(pid_str), "%lu", (unsigned long)getpid());
  163. len = write(lock->fd, pid_str, strlen(pid_str));
  164. if (len < 0) {
  165. msg_gerr("Cannot write PID to lockfile");
  166. return -1;
  167. }
  168. return 0;
  169. }
  170. static void file_lock_release(struct ipc_lock *lock)
  171. {
  172. if (flock(lock->fd, LOCK_UN) < 0)
  173. msg_gerr("Cannot release lock");
  174. if (close(lock->fd) < 0)
  175. msg_gerr("Cannot close lockfile");
  176. }
  177. /*
  178. * timeout <0 = no timeout (try forever)
  179. * timeout 0 = do not wait (return immediately)
  180. * timeout >0 = wait up to $timeout milliseconds
  181. *
  182. * returns 0 to indicate lock acquired
  183. * returns >0 to indicate lock was already held
  184. * returns <0 to indicate failed to acquire lock
  185. */
  186. int acquire_lock(struct ipc_lock *lock, int timeout_msecs)
  187. {
  188. /* check if it is already held */
  189. if (lock_is_held(lock))
  190. return 1;
  191. if (file_lock_open_or_create(lock))
  192. return -1;
  193. if (file_lock_get(lock, timeout_msecs)) {
  194. lock->is_held = 0;
  195. close(lock->fd);
  196. return -1;
  197. } else {
  198. lock->is_held = 1;
  199. }
  200. /*
  201. * Write PID to lockfile for debug purposes. Failure to write to
  202. * the file should not be considered fatal. There might be something
  203. * bad happening with the filesystem, but the lock has already been
  204. * obtained and we may need our tools for diagnostics and repairs
  205. * so we should continue anyway.
  206. */
  207. file_lock_write_pid(lock);
  208. return 0;
  209. }
  210. /*
  211. * returns 0 if lock was released successfully
  212. * returns -1 if lock had not been held before the call
  213. */
  214. int release_lock(struct ipc_lock *lock)
  215. {
  216. if (lock_is_held(lock)) {
  217. file_lock_release(lock);
  218. lock->is_held = 0;
  219. return 0;
  220. }
  221. msg_ginfo("%s called but lock was not held on %s.\n",
  222. __func__, lock->filename);
  223. return -1;
  224. }