file_lock: Add fallback directory

This adds a fallback directory in case SYSTEM_LOCKFILE_DIR is
unavailable. Since this is a band-aid meant to help older systems
auto-update, the fallback path is hardcoded to "/tmp" as to avoid
polluting the overall lockfile API.

BUG=chromium:616620
BRANCH=none
TEST=Tested on veyron_jaq by removing /run/lock and seeing
mosys, flashrom, and ectool run successfully with
firmware_utility_lock in /tmp.

Change-Id: Icba3381bfdc23673346d895b87b25afe3bfb8450
Signed-off-by: David Hendricks <dhendrix@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/348840
Reviewed-by: Hung-Te Lin <hungte@chromium.org>
Reviewed-by: Duncan Laurie <dlaurie@chromium.org>
diff --git a/core/file_lock.c b/core/file_lock.c
index ae8ec69..227fe00 100644
--- a/core/file_lock.c
+++ b/core/file_lock.c
@@ -73,6 +73,23 @@
 	return lock->is_held;
 }
 
+static int test_dir(const char *path)
+{
+	struct stat s;
+
+	if (lstat(path, &s) < 0) {
+		lperror(LOG_ERR, "Cannot stat %s.\n", path);
+		return -1;
+	}
+
+	if (!S_ISDIR(s.st_mode)) {
+		lprintf(LOG_ERR, "%s is not a directory.\n", path);
+		return -1;
+	}
+
+	return 0;
+}
+
 static int file_lock_open_or_create(struct ipc_lock *lock)
 {
 	struct stat s;
@@ -90,19 +107,22 @@
 			return -1;
 		}
 	} else {
+		const char fallback[] = "/tmp";
+
 		if (snprintf(path, sizeof(path), "%s/%s",
 				mosys_get_root_prefix(),
 				SYSTEM_LOCKFILE_DIR) < 0)
 			return -1;
 
-		if (lstat(path, &s) < 0) {
-			lperror(LOG_ERR, "Cannot stat %s", path);
-			return -1;
-		}
+		if (test_dir(path)) {
+			lprintf(LOG_ERR,
+				"Trying fallback directory: %s\n", fallback);
 
-		if (!S_ISDIR(s.st_mode)) {
-			lprintf(LOG_ERR, "%s is not a directory.\n", path);
-			return -1;
+			if (snprintf(path, sizeof(path), "%s/%s",
+					mosys_get_root_prefix(), fallback) < 0)
+				return -1;
+			if (test_dir(path))
+				return -1;
 		}
 
 		if (strlen(path) + strlen(lock->filename) + 2 > PATH_MAX) {