blob: 870e42c021896c3b3cb8d372452f675dabee8c17 [file] [log] [blame]
David Hendrickscb8ce142016-02-12 13:37:25 -08001/* 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
45#include <errno.h>
46#include <fcntl.h>
47#include <inttypes.h>
48#include <limits.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
52#include <time.h>
53#include <unistd.h>
54#include <sys/file.h>
55#include <sys/types.h>
56#include <sys/stat.h>
57
58#include "android.h"
59#include "flash.h"
60#include "ipc_lock.h"
61#include "locks.h"
62
63#define SLEEP_INTERVAL_MS 50
64
65static void msecs_to_timespec(int msecs, struct timespec *tmspec)
66{
67 tmspec->tv_sec = msecs / 1000;
68 tmspec->tv_nsec = (msecs % 1000) * 1000 * 1000;
69}
70
71static int lock_is_held(struct ipc_lock *lock)
72{
73 return lock->is_held;
74}
75
David Hendricks467b8252016-06-01 15:49:53 -070076static int test_dir(const char *path)
David Hendrickscb8ce142016-02-12 13:37:25 -080077{
78 struct stat s;
David Hendricks467b8252016-06-01 15:49:53 -070079
80 if (lstat(path, &s) < 0) {
81 msg_gerr("Cannot stat %s.\n", path);
82 return -1;
83 }
84
85 if (!S_ISDIR(s.st_mode)) {
86 msg_gerr("%s is not a directory.\n", path);
87 return -1;
88 }
89
90 return 0;
91}
92
93static int file_lock_open_or_create(struct ipc_lock *lock)
94{
David Hendrickscb8ce142016-02-12 13:37:25 -080095 char path[PATH_MAX];
96
97 if (in_android()) {
98 char *tmpdir;
99
100 tmpdir = android_tmpdir_path();
101 if (!tmpdir)
102 return -1;
103
104 if (snprintf(path, sizeof(path), "%s/%s",
105 tmpdir, lock->filename) < 0) {
106 return -1;
107 }
108 } else {
David Hendricks467b8252016-06-01 15:49:53 -0700109 const char *dir = SYSTEM_LOCKFILE_DIR;
110 const char fallback[] = "/tmp";
David Hendrickscb8ce142016-02-12 13:37:25 -0800111
David Hendricks467b8252016-06-01 15:49:53 -0700112 if (test_dir(dir)) {
113 dir = fallback;
114 msg_gerr("Trying fallback directory: %s\n", dir);
115 if (test_dir(dir))
116 return -1;
David Hendrickscb8ce142016-02-12 13:37:25 -0800117 }
118
David Hendricks467b8252016-06-01 15:49:53 -0700119 if (snprintf(path, sizeof(path),
120 "%s/%s", dir, lock->filename) < 0)
David Hendrickscb8ce142016-02-12 13:37:25 -0800121 return -1;
David Hendrickscb8ce142016-02-12 13:37:25 -0800122 }
123
124 lock->fd = open(path, O_RDWR | O_CREAT, 0600);
125 if (lock->fd < 0) {
126 msg_gerr("Cannot open lockfile %s", path);
127 return -1;
128 }
129
130 msg_gdbg("Opened file lock \"%s\"\n", path);
131 return 0;
132}
133
134static int file_lock_get(struct ipc_lock *lock, int timeout_msecs)
135{
136 int msecs_remaining = timeout_msecs;
137 struct timespec sleep_interval, rem;
138 int ret = -1;
139
140 if (timeout_msecs == 0)
141 return flock(lock->fd, LOCK_EX | LOCK_NB);
142
143 msecs_to_timespec(SLEEP_INTERVAL_MS, &sleep_interval);
144
145 while ((ret = flock(lock->fd, LOCK_EX | LOCK_NB)) != 0) {
146 if (errno != EWOULDBLOCK) {
147 msg_gerr("Error obtaining lock");
148 return -1;
149 }
150
151 if (msecs_remaining < SLEEP_INTERVAL_MS)
152 msecs_to_timespec(msecs_remaining, &sleep_interval);
153
154 while (nanosleep(&sleep_interval, &rem) != 0) {
155 if (errno == EINTR) {
156 sleep_interval = rem;
157 continue;
158 } else {
159 msg_gerr("nanosleep() failed");
160 return ret;
161 }
162 }
163
164 if (timeout_msecs < 0)
165 continue;
166
167 msecs_remaining -= SLEEP_INTERVAL_MS;
168 if (msecs_remaining < 0)
169 break;
170 }
171
172 if (ret != 0) {
173 msg_gerr("Timed out waiting for file lock.\n");
174 return -1;
175 }
176
177 return 0;
178}
179
180static int file_lock_write_pid(struct ipc_lock *lock)
181{
182 ssize_t len;
183 /* PIDs are usually 5 digits, but we'll reserve enough room for
184 a value of 2^32 (10 digits) out of paranoia. */
185 char pid_str[11];
186
187 if (ftruncate(lock->fd, 0) < 0) {
188 msg_gerr("Cannot truncate lockfile");
189 return -1;
190 }
191
192 snprintf(pid_str, sizeof(pid_str), "%lu", (unsigned long)getpid());
193 len = write(lock->fd, pid_str, strlen(pid_str));
194 if (len < 0) {
195 msg_gerr("Cannot write PID to lockfile");
196 return -1;
197 }
198
199 return 0;
200}
201
202static void file_lock_release(struct ipc_lock *lock)
203{
204 if (flock(lock->fd, LOCK_UN) < 0)
205 msg_gerr("Cannot release lock");
206
207 if (close(lock->fd) < 0)
208 msg_gerr("Cannot close lockfile");
209}
210
211/*
212 * timeout <0 = no timeout (try forever)
213 * timeout 0 = do not wait (return immediately)
214 * timeout >0 = wait up to $timeout milliseconds
215 *
216 * returns 0 to indicate lock acquired
217 * returns >0 to indicate lock was already held
218 * returns <0 to indicate failed to acquire lock
219 */
220int acquire_lock(struct ipc_lock *lock, int timeout_msecs)
221{
222 /* check if it is already held */
223 if (lock_is_held(lock))
224 return 1;
225
226 if (file_lock_open_or_create(lock))
227 return -1;
228
229 if (file_lock_get(lock, timeout_msecs)) {
230 lock->is_held = 0;
231 close(lock->fd);
232 return -1;
233 } else {
234 lock->is_held = 1;
235 }
236
237 /*
238 * Write PID to lockfile for debug purposes. Failure to write to
239 * the file should not be considered fatal. There might be something
240 * bad happening with the filesystem, but the lock has already been
241 * obtained and we may need our tools for diagnostics and repairs
242 * so we should continue anyway.
243 */
244 file_lock_write_pid(lock);
245 return 0;
246}
247
248/*
249 * returns 0 if lock was released successfully
250 * returns -1 if lock had not been held before the call
251 */
252int release_lock(struct ipc_lock *lock)
253{
254 if (lock_is_held(lock)) {
255 file_lock_release(lock);
256 lock->is_held = 0;
257 return 0;
258 }
259
260 msg_ginfo("%s called but lock was not held on %s.\n",
261 __func__, lock->filename);
262 return -1;
263}