1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <android-base/file.h>
18 #include <android-base/logging.h>
19
20 #include <fstream>
21 #include <iterator>
22
23 #include "storage.h"
24 #include "util.h"
25
ConnectedDevicesStorage()26 ConnectedDevicesStorage::ConnectedDevicesStorage() {
27 home_fastboot_path_ = GetHomeDirPath() + kPathSeparator + ".fastboot";
28 devices_path_ = home_fastboot_path_ + kPathSeparator + "devices";
29
30 // We're using a separate file for locking because the Windows LockFileEx does not
31 // permit opening a file stream for the locked file, even within the same process. So,
32 // we have to use fd or handle API to manipulate the storage files, which makes it
33 // nearly impossible to fully rewrite a file content without having to recreate it.
34 // Unfortunately, this is not an option during holding a lock.
35 devices_lock_path_ = home_fastboot_path_ + kPathSeparator + "devices.lock";
36 }
37
Exists() const38 bool ConnectedDevicesStorage::Exists() const {
39 return FileExists(devices_path_);
40 }
41
WriteDevices(const FileLock &,const std::set<std::string> & devices)42 void ConnectedDevicesStorage::WriteDevices(const FileLock&, const std::set<std::string>& devices) {
43 std::ofstream devices_stream(devices_path_);
44 std::copy(devices.begin(), devices.end(),
45 std::ostream_iterator<std::string>(devices_stream, "\n"));
46 }
47
ReadDevices(const FileLock &)48 std::set<std::string> ConnectedDevicesStorage::ReadDevices(const FileLock&) {
49 std::ifstream devices_stream(devices_path_);
50 std::istream_iterator<std::string> start(devices_stream), end;
51 std::set<std::string> devices(start, end);
52 return devices;
53 }
54
Clear(const FileLock &)55 void ConnectedDevicesStorage::Clear(const FileLock&) {
56 if (!android::base::RemoveFileIfExists(devices_path_)) {
57 LOG(FATAL) << "Failed to clear connected device list: " << devices_path_;
58 }
59 }
60
Lock() const61 FileLock ConnectedDevicesStorage::Lock() const {
62 if (!EnsureDirectoryExists(home_fastboot_path_)) {
63 LOG(FATAL) << "Cannot create directory: " << home_fastboot_path_;
64 }
65 return FileLock(devices_lock_path_);
66 }
67