1 /*
2  * Copyright (C) 2017 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 "uevent_listener.h"
18 
19 #include <fcntl.h>
20 #include <poll.h>
21 #include <string.h>
22 #include <unistd.h>
23 
24 #include <memory>
25 
26 #include <android-base/logging.h>
27 #include <cutils/uevent.h>
28 
29 namespace android {
30 namespace init {
31 
ParseEvent(const char * msg,Uevent * uevent)32 static void ParseEvent(const char* msg, Uevent* uevent) {
33     uevent->partition_num = -1;
34     uevent->major = -1;
35     uevent->minor = -1;
36     uevent->action.clear();
37     uevent->path.clear();
38     uevent->subsystem.clear();
39     uevent->firmware.clear();
40     uevent->partition_name.clear();
41     uevent->device_name.clear();
42     uevent->modalias.clear();
43     // currently ignoring SEQNUM
44     while (*msg) {
45         if (!strncmp(msg, "ACTION=", 7)) {
46             msg += 7;
47             uevent->action = msg;
48         } else if (!strncmp(msg, "DEVPATH=", 8)) {
49             msg += 8;
50             uevent->path = msg;
51         } else if (!strncmp(msg, "SUBSYSTEM=", 10)) {
52             msg += 10;
53             uevent->subsystem = msg;
54         } else if (!strncmp(msg, "FIRMWARE=", 9)) {
55             msg += 9;
56             uevent->firmware = msg;
57         } else if (!strncmp(msg, "MAJOR=", 6)) {
58             msg += 6;
59             uevent->major = atoi(msg);
60         } else if (!strncmp(msg, "MINOR=", 6)) {
61             msg += 6;
62             uevent->minor = atoi(msg);
63         } else if (!strncmp(msg, "PARTN=", 6)) {
64             msg += 6;
65             uevent->partition_num = atoi(msg);
66         } else if (!strncmp(msg, "PARTNAME=", 9)) {
67             msg += 9;
68             uevent->partition_name = msg;
69         } else if (!strncmp(msg, "DEVNAME=", 8)) {
70             msg += 8;
71             uevent->device_name = msg;
72         } else if (!strncmp(msg, "MODALIAS=", 9)) {
73             msg += 9;
74             uevent->modalias = msg;
75         }
76 
77         // advance to after the next \0
78         while (*msg++)
79             ;
80     }
81 
82     if (LOG_UEVENTS) {
83         LOG(INFO) << "event { '" << uevent->action << "', '" << uevent->path << "', '"
84                   << uevent->subsystem << "', '" << uevent->firmware << "', " << uevent->major
85                   << ", " << uevent->minor << " }";
86     }
87 }
88 
UeventListener(size_t uevent_socket_rcvbuf_size)89 UeventListener::UeventListener(size_t uevent_socket_rcvbuf_size) {
90     device_fd_.reset(uevent_open_socket(uevent_socket_rcvbuf_size, true));
91     if (device_fd_ == -1) {
92         LOG(FATAL) << "Could not open uevent socket";
93     }
94 
95     fcntl(device_fd_, F_SETFL, O_NONBLOCK);
96 }
97 
ReadUevent(Uevent * uevent) const98 ReadUeventResult UeventListener::ReadUevent(Uevent* uevent) const {
99     char msg[UEVENT_MSG_LEN + 2];
100     int n = uevent_kernel_multicast_recv(device_fd_, msg, UEVENT_MSG_LEN);
101     if (n <= 0) {
102         if (errno != EAGAIN && errno != EWOULDBLOCK) {
103             PLOG(ERROR) << "Error reading from Uevent Fd";
104         }
105         return ReadUeventResult::kFailed;
106     }
107     if (n >= UEVENT_MSG_LEN) {
108         LOG(ERROR) << "Uevent overflowed buffer, discarding";
109         return ReadUeventResult::kInvalid;
110     }
111 
112     msg[n] = '\0';
113     msg[n + 1] = '\0';
114 
115     ParseEvent(msg, uevent);
116 
117     return ReadUeventResult::kSuccess;
118 }
119 
120 // RegenerateUevents*() walks parts of the /sys tree and pokes the uevent files to cause the kernel
121 // to regenerate device add uevents that have already happened.  This is particularly useful when
122 // starting ueventd, to regenerate all of the uevents that it had previously missed.
123 //
124 // We drain any pending events from the netlink socket every time we poke another uevent file to
125 // make sure we don't overrun the socket's buffer.
126 //
127 
RegenerateUeventsForDir(DIR * d,const ListenerCallback & callback) const128 ListenerAction UeventListener::RegenerateUeventsForDir(DIR* d,
129                                                        const ListenerCallback& callback) const {
130     int dfd = dirfd(d);
131 
132     int fd = openat(dfd, "uevent", O_WRONLY | O_CLOEXEC);
133     if (fd >= 0) {
134         write(fd, "add\n", 4);
135         close(fd);
136 
137         Uevent uevent;
138         ReadUeventResult result;
139         while ((result = ReadUevent(&uevent)) != ReadUeventResult::kFailed) {
140             // Skip processing the uevent if it is invalid.
141             if (result == ReadUeventResult::kInvalid) continue;
142             if (callback(uevent) == ListenerAction::kStop) return ListenerAction::kStop;
143         }
144     }
145 
146     dirent* de;
147     while ((de = readdir(d)) != nullptr) {
148         if (de->d_type != DT_DIR || de->d_name[0] == '.') continue;
149 
150         fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
151         if (fd < 0) continue;
152 
153         std::unique_ptr<DIR, decltype(&closedir)> d2(fdopendir(fd), closedir);
154         if (d2 == 0) {
155             close(fd);
156         } else {
157             if (RegenerateUeventsForDir(d2.get(), callback) == ListenerAction::kStop) {
158                 return ListenerAction::kStop;
159             }
160         }
161     }
162 
163     // default is always to continue looking for uevents
164     return ListenerAction::kContinue;
165 }
166 
RegenerateUeventsForPath(const std::string & path,const ListenerCallback & callback) const167 ListenerAction UeventListener::RegenerateUeventsForPath(const std::string& path,
168                                                         const ListenerCallback& callback) const {
169     std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
170     if (!d) return ListenerAction::kContinue;
171 
172     return RegenerateUeventsForDir(d.get(), callback);
173 }
174 
175 static const char* kRegenerationPaths[] = {"/sys/devices"};
176 
RegenerateUevents(const ListenerCallback & callback) const177 void UeventListener::RegenerateUevents(const ListenerCallback& callback) const {
178     for (const auto path : kRegenerationPaths) {
179         if (RegenerateUeventsForPath(path, callback) == ListenerAction::kStop) return;
180     }
181 }
182 
Poll(const ListenerCallback & callback,const std::optional<std::chrono::milliseconds> relative_timeout) const183 void UeventListener::Poll(const ListenerCallback& callback,
184                           const std::optional<std::chrono::milliseconds> relative_timeout) const {
185     using namespace std::chrono;
186 
187     pollfd ufd;
188     ufd.events = POLLIN;
189     ufd.fd = device_fd_;
190 
191     auto start_time = steady_clock::now();
192 
193     while (true) {
194         ufd.revents = 0;
195 
196         int timeout_ms = -1;
197         if (relative_timeout) {
198             auto now = steady_clock::now();
199             auto time_elapsed = duration_cast<milliseconds>(now - start_time);
200             if (time_elapsed > *relative_timeout) return;
201 
202             auto remaining_timeout = *relative_timeout - time_elapsed;
203             timeout_ms = remaining_timeout.count();
204         }
205 
206         int nr = poll(&ufd, 1, timeout_ms);
207         if (nr == 0) return;
208         if (nr < 0) {
209             PLOG(ERROR) << "poll() of uevent socket failed, continuing";
210             continue;
211         }
212         if (ufd.revents & POLLIN) {
213             // We're non-blocking, so if we receive a poll event keep processing until
214             // we have exhausted all uevent messages.
215             Uevent uevent;
216             ReadUeventResult result;
217             while ((result = ReadUevent(&uevent)) != ReadUeventResult::kFailed) {
218                 // Skip processing the uevent if it is invalid.
219                 if (result == ReadUeventResult::kInvalid) continue;
220                 if (callback(uevent) == ListenerAction::kStop) return;
221             }
222         }
223     }
224 }
225 
226 }  // namespace init
227 }  // namespace android
228