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 bool 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 LOG(ERROR) << "Error reading from Uevent Fd";
104 }
105 return false;
106 }
107 if (n >= UEVENT_MSG_LEN) {
108 LOG(ERROR) << "Uevent overflowed buffer, discarding";
109 // Return true here even if we discard as we may have more uevents pending and we
110 // want to keep processing them.
111 return true;
112 }
113
114 msg[n] = '\0';
115 msg[n + 1] = '\0';
116
117 ParseEvent(msg, uevent);
118
119 return true;
120 }
121
122 // RegenerateUevents*() walks parts of the /sys tree and pokes the uevent files to cause the kernel
123 // to regenerate device add uevents that have already happened. This is particularly useful when
124 // starting ueventd, to regenerate all of the uevents that it had previously missed.
125 //
126 // We drain any pending events from the netlink socket every time we poke another uevent file to
127 // make sure we don't overrun the socket's buffer.
128 //
129
RegenerateUeventsForDir(DIR * d,const ListenerCallback & callback) const130 ListenerAction UeventListener::RegenerateUeventsForDir(DIR* d,
131 const ListenerCallback& callback) const {
132 int dfd = dirfd(d);
133
134 int fd = openat(dfd, "uevent", O_WRONLY);
135 if (fd >= 0) {
136 write(fd, "add\n", 4);
137 close(fd);
138
139 Uevent uevent;
140 while (ReadUevent(&uevent)) {
141 if (callback(uevent) == ListenerAction::kStop) return ListenerAction::kStop;
142 }
143 }
144
145 dirent* de;
146 while ((de = readdir(d)) != nullptr) {
147 if (de->d_type != DT_DIR || de->d_name[0] == '.') continue;
148
149 fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY);
150 if (fd < 0) continue;
151
152 std::unique_ptr<DIR, decltype(&closedir)> d2(fdopendir(fd), closedir);
153 if (d2 == 0) {
154 close(fd);
155 } else {
156 if (RegenerateUeventsForDir(d2.get(), callback) == ListenerAction::kStop) {
157 return ListenerAction::kStop;
158 }
159 }
160 }
161
162 // default is always to continue looking for uevents
163 return ListenerAction::kContinue;
164 }
165
RegenerateUeventsForPath(const std::string & path,const ListenerCallback & callback) const166 ListenerAction UeventListener::RegenerateUeventsForPath(const std::string& path,
167 const ListenerCallback& callback) const {
168 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
169 if (!d) return ListenerAction::kContinue;
170
171 return RegenerateUeventsForDir(d.get(), callback);
172 }
173
174 static const char* kRegenerationPaths[] = {"/sys/class", "/sys/block", "/sys/devices"};
175
RegenerateUevents(const ListenerCallback & callback) const176 void UeventListener::RegenerateUevents(const ListenerCallback& callback) const {
177 for (const auto path : kRegenerationPaths) {
178 if (RegenerateUeventsForPath(path, callback) == ListenerAction::kStop) return;
179 }
180 }
181
Poll(const ListenerCallback & callback,const std::optional<std::chrono::milliseconds> relative_timeout) const182 void UeventListener::Poll(const ListenerCallback& callback,
183 const std::optional<std::chrono::milliseconds> relative_timeout) const {
184 using namespace std::chrono;
185
186 pollfd ufd;
187 ufd.events = POLLIN;
188 ufd.fd = device_fd_;
189
190 auto start_time = steady_clock::now();
191
192 while (true) {
193 ufd.revents = 0;
194
195 int timeout_ms = -1;
196 if (relative_timeout) {
197 auto now = steady_clock::now();
198 auto time_elapsed = duration_cast<milliseconds>(now - start_time);
199 if (time_elapsed > *relative_timeout) return;
200
201 auto remaining_timeout = *relative_timeout - time_elapsed;
202 timeout_ms = remaining_timeout.count();
203 }
204
205 int nr = poll(&ufd, 1, timeout_ms);
206 if (nr == 0) return;
207 if (nr < 0) {
208 PLOG(ERROR) << "poll() of uevent socket failed, continuing";
209 continue;
210 }
211 if (ufd.revents & POLLIN) {
212 // We're non-blocking, so if we receive a poll event keep processing until
213 // we have exhausted all uevent messages.
214 Uevent uevent;
215 while (ReadUevent(&uevent)) {
216 if (callback(uevent) == ListenerAction::kStop) return;
217 }
218 }
219 }
220 }
221
222 } // namespace init
223 } // namespace android
224