blob: 5b9eceaa988f0564a571f865302a64cb39d2411b [file] [log] [blame]
Roman Stratiienkobd973172022-02-18 16:51:53 +02001/*
2 * Copyright (C) 2022 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#pragma once
18
19#include <linux/netlink.h>
20#include <sys/socket.h>
21
22#include <cerrno>
23#include <memory>
24#include <optional>
25#include <string>
26
Roman Stratiienko76892782023-01-16 17:15:53 +020027#include "fd.h"
Roman Stratiienkobd973172022-02-18 16:51:53 +020028#include "log.h"
29
30namespace android {
31
32class UEvent {
33 public:
34 static auto CreateInstance() -> std::unique_ptr<UEvent> {
Roman Stratiienko76892782023-01-16 17:15:53 +020035 auto fd = MakeUniqueFd(
Roman Stratiienkobd973172022-02-18 16:51:53 +020036 socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT));
37
38 if (!fd) {
39 ALOGE("Failed to open uevent socket: errno=%i", errno);
40 return {};
41 }
42
43 struct sockaddr_nl addr {};
44 addr.nl_family = AF_NETLINK;
45 addr.nl_pid = 0;
46 addr.nl_groups = UINT32_MAX;
47
48 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
Roman Stratiienko76892782023-01-16 17:15:53 +020049 const int ret = bind(*fd, (struct sockaddr *)&addr, sizeof(addr));
Roman Stratiienkobd973172022-02-18 16:51:53 +020050 if (ret != 0) {
51 ALOGE("Failed to bind uevent socket: errno=%i", errno);
52 return {};
53 }
54
55 return std::unique_ptr<UEvent>(new UEvent(fd));
56 }
57
58 auto ReadNext() -> std::optional<std::string> {
59 constexpr int kUEventBufferSize = 1024;
60 char buffer[kUEventBufferSize];
61 ssize_t ret = 0;
Roman Stratiienko76892782023-01-16 17:15:53 +020062 ret = read(*fd_, &buffer, sizeof(buffer));
Roman Stratiienkobd973172022-02-18 16:51:53 +020063 if (ret == 0)
64 return {};
65
66 if (ret < 0) {
67 ALOGE("Got error reading uevent %zd", ret);
68 return {};
69 }
70
71 for (int i = 0; i < ret - 1; i++) {
72 if (buffer[i] == '\0') {
73 buffer[i] = '\n';
74 }
75 }
76
77 return std::string(buffer);
78 }
79
80 private:
81 explicit UEvent(UniqueFd &fd) : fd_(std::move(fd)){};
82 UniqueFd fd_;
83};
84
85} // namespace android