1 // Copyright (C) 2020 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #pragma once
16 
17 #include <unistd.h>
18 
19 #include <chrono>
20 #include <cstring>
21 #include <iostream>
22 #include <string>
23 #include <thread>
24 #include <vector>
25 
26 #include <android-base/unique_fd.h>
27 
28 namespace android {
29 namespace snapshot {
30 
31 static constexpr uint32_t PACKET_SIZE = 512;
32 
33 static constexpr char kSnapuserdSocket[] = "snapuserd";
34 
35 // Ensure that the second-stage daemon for snapuserd is running.
36 bool EnsureSnapuserdStarted();
37 
38 class SnapuserdClient {
39   private:
40     android::base::unique_fd sockfd_;
41 
42     bool Sendmsg(const std::string& msg);
43     std::string Receivemsg();
44 
45     bool ValidateConnection();
46 
47   public:
48     explicit SnapuserdClient(android::base::unique_fd&& sockfd);
49 
50     static std::unique_ptr<SnapuserdClient> Connect(const std::string& socket_name,
51                                                     std::chrono::milliseconds timeout_ms);
52 
53     bool StopSnapuserd();
54 
55     // Initializing a snapuserd handler is a three-step process:
56     //
57     //  1. Client invokes InitDmUserCow. This creates the snapuserd handler and validates the
58     //     COW. The number of sectors required for the dm-user target is returned.
59     //  2. Client creates the device-mapper device with the dm-user target.
60     //  3. Client calls AttachControlDevice.
61     //
62     // The misc_name must be the "misc_name" given to dm-user in step 2.
63     //
64     uint64_t InitDmUserCow(const std::string& misc_name, const std::string& cow_device,
65                            const std::string& backing_device);
66     bool AttachDmUser(const std::string& misc_name);
67 
68     // Wait for snapuserd to disassociate with a dm-user control device. This
69     // must ONLY be called if the control device has already been deleted.
70     bool WaitForDeviceDelete(const std::string& control_device);
71 
CloseConnection()72     void CloseConnection() { sockfd_ = {}; }
73 
74     // Detach snapuserd. This shuts down the listener socket, and will cause
75     // snapuserd to gracefully exit once all handler threads have terminated.
76     // This should only be used on first-stage instances of snapuserd.
77     bool DetachSnapuserd();
78 };
79 
80 }  // namespace snapshot
81 }  // namespace android
82